4 ms·
> It's kind of sad that "for" is the keyword programming languages settled on for the loop construct. Many languages only use `for` to mean a for-each style lo
by laurencerowe 6y ago
> It's kind of sad that "for" is the keyword programming languages settled on for the loop construct.
Many languages only use `for` to mean a for-each style loop where it reads quite naturally:
Python - `for n in range(1,10)`
Ruby - `for i in 0..10`
Rust - `for n in 1..10` (also picked up the bare `loop`)
Others support for-each style loops along with the less than ideal C-style for loop:
JavaScript - `for (n of [1,2,3])` (second attempt, for-in has too many gotchas.)
Java - `for (int n : {1,2,3})`
Otherwise I agree that `while` reads far more naturally. I guess they must have wanted to minimize the number keywords in Go.
- UIZealot 6y agoIt's only natural if you already know that a for-statement is a loop. "while" is no better without the "do".
- stevewodil 6y agoAnd if statements need a corresponding "then" to make sense as well right? Your whole argument is nonsensical. Coding isn't English Write a new language and you can name everything exactly how you please, if enough people care then they will adopt the language.
- saghm 6y agoInterestingly, 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.
- laurencerowe 6y agoIt's been years since I last wrote Ruby so had completely forgotten that it's ranges were inclusive by default.
- Lammy 6y agoYou can kinda use `do` for looping with a Block and Kernel#loop :v https://ruby-doc.org/core-2.7.1/Kernel.html#method-i-loop https://ruby-doc.org/core-2.7.1/Kernel.html#method-i-loop