Stok Footage

Continually experimenting with new ideas and techniques — Reconstructing, Developing, Modernising.

Code Nugget of the Day

The Ruby language mailing list is often a source of gentle reminders about things I might have missed, and I read Robert Klemme’s with particular interest. One of his recent posts was a nice reminder of a way to initialise an array without using map, which is where I usually end up when I don’t think:

1
2
3
ratdog:~ mike$ pry --simple-prompt
>> odds = (0 .. 9).map { |i| i * 2 + 1 }
=> [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

Ruby’s core documentation for Array.new mentions the form Array.new(size) {|index| block }, so we can do something like:

4
5
>> odds = Array.new(10) { |i| i * 2 + 1 }
=> [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

I could use an Enumerator to generate a list of odd numbers, and take the first ten:

6
7
8
9
>> odd_gen = Enumerator.new { |y| n = 0 ; loop { y.yield n * 2 + 1; n += 1 } }
=> #<Enumerator: ...>
>> odd_gen.take 10
=> [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

Hmmm… maybe this is not a good case for Enumerator — it’s always good to go for simple where possible!

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *