Search code examples
rubyarraysnotation

Is there a %w{ }--like way to create array of fixnums in Ruby?


Is there a way to create an array of Fixnums using ruby's % notation?

It's obviously quite trivial to write, for example [edit: changed example to nonconsecutive digits]

digits = %w{4 8 15 16 23 42}.map{|d| d.to_i}

=> [4, 8, 15, 16, 23, 42]

but it bugs me and I'm wondering if there is a way to do it without the map. None of these sources mention such a possibility---am I out of luck?

What does %w(array) mean?

What is the %w "thing" in ruby?

Ruby Programming Syntax - the % notation


Solution

  • Since the % notation seems to be one of those "bastard" Perl string handling inheritances in Ruby I strongly doubt it but you can save a couple of characters by

    digits = %w{1 2 3 4 5 6 7 8 9 10}.map(&:to_i)