简体   繁体   English

使用范围类而不是fixnum的红宝石for循环?

[英]ruby for loop using range class instead of fixnum?

for i in [0..4] do
  puts i + 1
end

undefined method `+' for 0..4:Range (NoMethodError) 未定义的方法'+'表示0..4:Range(NoMethodError)

Why is it not treating each number in the range as a fixnum within the loop? 为什么不将范围内的每个数字都视为循环中的fixnum?

[0..4] is actually array with one range element, the same as [(0..4)] . [0..4]实际上是具有一个范围元素的数组,与[(0..4)] You need to change it to (0..4) . 您需要将其更改为(0..4)

Write instead: 改为写:

for i in 0..4 do

Otherwise you don't have a range, you have an array containing 1 range. 否则,您将没有范围,则您将有一个包含1个范围的数组。

There are different ways to achive a goal: 有多种方法可以达成目标:

0.upto(4) { |i|
  puts i
}

0.step(4, 1) { |i|
  puts i
}

5.times { |i| # 5 for inclusive
  puts i
}

for i in 0..4
  puts i
end

Everything will output: 一切都会输出:

# ⇒ 0
# ⇒ 1
# ⇒ 2
# ⇒ 3
# ⇒ 4

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM