omikes
omikes

Reputation: 8513

How do I nicely instantiate an array of specific numbers in Ruby?

I know with strings its as simple as this:

string_array = %w(list of strings)

but is there something similar for integers?

number_array = %i(1 2 3)

Upvotes: 0

Views: 44

Answers (1)

tadman
tadman

Reputation: 211560

There's no short-hand for this because you can approach it one of two ways:

number_array = [ 1, 2, 3 ]

That's the conventional approach. A %w approach looks like this:

number_array = %w[ 1 2 3 ].map(&:to_i)

Either way is equivalent but the former is slightly more efficient if you're doing this very frequently.

Upvotes: 3

Related Questions