2

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

Community
  • 1
  • 1
eulerz
  • 23
  • 4

5 Answers5

4

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)
Jonas Elfström
  • 30,834
  • 6
  • 70
  • 106
  • Ooh, I wasn't aware of that syntax possibility. Nice. – eulerz Oct 04 '11 at 19:15
  • 1
    It's called Symbol#to_proc and the wonderful @raganwald / Reginald Braithwaite taught me about it back in 2007. http://weblog.raganwald.com/2007/10/stringtoproc.html It's part of Ruby 1.9 and I think it's been backported to 1.8 as well. – Jonas Elfström Oct 04 '11 at 19:26
  • I can confirm it exists in 1.8.7 even without Rails. – Andrew Grimm Oct 04 '11 at 21:44
2

The % notation is specifically about strings, so that won't help you get any closer than the example you gave.

If the integers you care about are consecutive, you could use a Range object:

(1..10).to_a
Jacob Mattison
  • 50,258
  • 9
  • 107
  • 126
2

Am I missing something or does

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

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

not do it?

Excellent choice of numbers, btw :)

dantswain
  • 5,427
  • 1
  • 29
  • 37
  • 1
    :-) and no, you're perfectly correct. That's the 'normal' way to do it. But all those commas! Such a pain! – eulerz Oct 06 '11 at 21:35
0
Array.new(10) {|i| i}

It's a way of doing it without map.

lucapette
  • 20,564
  • 6
  • 65
  • 59
  • Well, yes, in the case of my made-up-for-the-example array that works fine, but I was rather hoping for more of a... general solution. – eulerz Oct 04 '11 at 19:14
0

You could edit parse.y, which turns source code into Ruby, and then re-compile Ruby. I've never edited parse.y myself, but here's an amusing and awesome talk at RubyKaigi2011 about it.

Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338