mbigras
mbigras

Reputation: 8055

How to use percent notation to make an array of integers in ruby?

In ruby you can use percent notation to easily make an array of strings:

[14] pry(main)> %w(some cats ran far)
=> ["some", "cats", "ran", "far"]

Using a method found in another post I was able to make an array of strings using percent notation and then converting them into Fixnums later:

[15] pry(main)> %w(1 2 3).map(&:to_i)
=> [1, 2, 3]

But I'd really like to be able to do something like

%i(1 2 3) #=> [1 2 3]

Is this possible? Thanks :)

Upvotes: 14

Views: 8929

Answers (3)

Mike S
Mike S

Reputation: 11409

As cremno said, no that is not possible.

If you want strictly a range of integers, such as 1 through 10, the best method will be

(1..10).to_a
# => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

But if you want to specify exact integers I would do this

%w(1 5 10).map{|i| i.to_i}
# => [1, 5, 10]

But at that point I don't know why you wouldn't just do this directly...

[1, 5, 10]

Upvotes: 13

mbigras
mbigras

Reputation: 8055

Using a range seems like it might be the easiest:

[26] pry(main)> (1..3).to_a
=> [1, 2, 3]

Upvotes: 0

alexdotsh
alexdotsh

Reputation: 176

Well, you can do something like this.

%i(1 2 3).map(&:to_s).map { |i| Integer(i) } #=> [1, 2, 3]

Upvotes: 0

Related Questions