|
|
|
|
|
by saghm
2144 days ago
|
|
Interestingly, the more common way to write that in Ruby would be `(1..10).each { |i| ... }`, or (in the case of needing a multi-line block): ```
(1..10).each do |i|
...
end
``` "do" does end up getting used, but only as syntax for a "block" (similar to what other languages would call a lambda). Ruby also has a shorthand for when you want to do something `n` times without caring about the iteration number: ```
10.times do
...
end
``` One final note is that loop you wrote above is actually different in Ruby than it is for Python and Rust; `x..y` is an inclusive range in Ruby, whereas `range(x, y)` in Python and `x..y` in Rust are exclusive on the right side. I think you might have realized that since you used different starting values for the other two, but you got it backwards; the Python and Rust loops will loop only nine times, whereas the Ruby one will loop 11 times. Ruby does have a syntax for exclusive ranges though; `x...y` is an inclusive range from `x` to `y - 1`. Similarly, in Rust, `x..=y` gives an inclusive range from `x` to `y`. I don't know of any way to do an inclusive range in Python other than manually, but someone with more Python knowledge might be able to provide something for that. |
|