开发者

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开发者_如何学JAVA 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


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)


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 :)


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


Array.new(10) {|i| i}

It's a way of doing it without map.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜