Ruby Idioms, Part 5

Written on 7:43:00 PM by S. Potter

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 post Subscribe to our feed

2 Comments

  1. John |

    Your idiom reminded me of lazylist. Lazylist appeals to me and I thought I'd contribute this expression:


    require 'rubygems'
    require 'lazylist'

    odds = list {x}.where(:x => 1..1001) {x % 2 == 1}



    Note: lazylist is not in the core api.


    This doesn't read like natural
    language so maybe not too favorable to the goal of your blog. Maybe it can be read as: odds is a list of x where, for each x, from 1 to 1001, {x % 2 == 1} evaluates to true.

    http://lazylist.rubyforge.org/

    Regards.

     
  2. S. Potter |

    Thanks! I love hearing about new ways (and libraries) to do even the smallest things in a more terse and readable fashion.

     

Post a Comment