Some of you may say this isn't strictly an idiom, but it is dependent
on Ruby's core API and classes, so I have included it. Ranges are a
very nice low-level abstraction and can save Ruby developers a lot of
time for certain coding needs. In a previous idiom example on this
blog I had a list of positive odd numbers under 7. Well typing this
out by hand is hardly consuming so I typed [1, 3, 5]
by hand.
However, say we wanted to check if a number given by the user is an
odd number under, say, 1001. How can we do that in as few lines of
code, while still maintaining or even enhancing code readability?
Look no further:
ls = []
(1...1001).step(2) {|x| ls << x} #=> [1, 3, ..., 997, 999]
For Java heads that don't understand blocks - too bad that is out of the scope of this blog entry:) Go and do you homework then revisit. Google should be able to help you out in this regard.
Of course, Ruby developers could and would debate whether my solution above is the "best", concerning how terse and readable it is since there are so many ways of doing this that provide a decent solution. There may even be another solution in the Ruby universe I may prefer, but at present this maintains readability to a high standard (assuming you understand blocks, of course), again in my opinion. I may even expand the code as follows to make it truly readable:
ls = []
(1...1001).step(2) do |x|
ls << x
end #=> [1, 3, ..., 997, 999]
What are a couple of extra lines to make something as readable as possible anyway?
If you enjoyed this content, please consider sharing this link with a friend, following my GitHub, Twitter/X or LinkedIn accounts, or subscribing to my RSS feed.