Ruby编程之while循环与枚举
【摘要】 笔者主要介绍了Ruby编程之while循环与枚举
x = 100
# The code in this loop never runs
while (x < 100) do puts('x < 100') end
# The code in this loop never runs
puts('x < 100') while (x < 100)
# But the code in loop runs once
begin puts('x < 100') end while (x < 100)
x < 100
i = 10
until i == 10 do puts(i) end # never executes
until i == 10 # never executes
puts(i)
i += 1
end
puts(i) until i == 10 # never executes
begin # executes once
puts(i)
end until i == 10
10
arr= [1,2,3,4,5]
i = 0
while i < arr.length
puts(arr[i])
i += 1
end
i=0
until i == arr.length
puts(arr[i])
i +=1
end
1
2
3
4
5
1
2
3
4
5
x = (1..5).collect{ |i| i }
p( x ) #=> [1, 2, 3, 4, 5]
arr = [1,2,3,4,5]
y = arr.collect{ |i| i }
p( y ) #=> [1, 2, 3, 4, 5]
z = arr.collect{ |i| i * i }
p( z ) #=> [1, 4, 9, 16, 25]
p( arr.include?( 3 ) ) #=> true
p( arr.include?( 6 ) ) #=> false
p( arr.min ) #=> 1
p( arr.max ) #=> 5
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[1, 4, 9, 16, 25]
true
false
1
5
h = {'one'=>'for sorrow',
'two'=>'for joy',
'three'=>'for a girl',
'four'=>'for a boy'}
y = h.collect{ |i| i }
p( y )
[["one", "for sorrow"], ["two", "for joy"], ["three", "for a girl"], ["four", "for a boy"]]
p( h.min ) #=> ["one", "for sorrow"]
p( h.max ) #=> ["two", "for joy"]
["four", "for a boy"]
["two", "for joy"]
h.sort{ |a,b| a.to_s <=> b.to_s }
p(h)
h.min{ |a,b| a[0].length <=> b[0].length }
p(h)
h.max{|a,b| a[0].length <=> b[0].length }
p(h)
a = ['one', 'for sorrow']
b = ['two', 'for joy']
p(a[0].length <=> b[0].length)
{"one"=>"for sorrow", "two"=>"for joy", "three"=>"for a girl", "four"=>"for a boy"}
{"one"=>"for sorrow", "two"=>"for joy", "three"=>"for a girl", "four"=>"for a boy"}
{"one"=>"for sorrow", "two"=>"for joy", "three"=>"for a girl", "four"=>"for a boy"}
0
开发环境:Rubymine
The book of Ruby----A hands-on guide for the Adventurous---[美]Huw Collingbourne---no starch press
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区),文章链接,文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件至:cloudbbs@huaweicloud.com进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容。
- 点赞
- 收藏
- 关注作者
评论(0)