码迷,mamicode.com
首页 > 其他好文 > 详细

Ruby - Looping

时间:2016-07-19 22:10:27      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:

 

While

counter = 1
while counter < 11
  puts counter
  counter = counter + 1
end

 

Until

i = 0
until i == 6
  i += 1
end
puts i

 

For

for num in 1...10
  puts num
end

for numin 1...10 means "go up to but don‘t include 10." If we use two dots, this tells Ruby to include the highest number in the range.

 

iterator

i = 20
loop do
  i -= 1
  print "#{i}"
  break if i <= 0
end

 

next

for i in 1..5
  next if i % 2 == 0
  print i
end

 

.each iterator

object.each { |item| # Do something }

You can also use the do keyword instead of {}:

object.each do |item| # Do something end

The variable name between | | can be anything you like: it‘s just a placeholder for each element of the object you‘re using .each on.

 

array = [1,2,3,4,5]

array.each do |x|
  x += 10
  print "#{x}"
end

 

.times iterator

10.times {print "haha"}

 

Ruby - Looping

标签:

原文地址:http://www.cnblogs.com/elewei/p/5686410.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!