Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

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

like image 345
mbigras Avatar asked Jun 16 '16 21:06

mbigras


People also ask

What is W [] in Ruby?

Save this answer. Show activity on this post. %w(foo bar) is a shortcut for ["foo", "bar"] . Meaning it's a notation to write an array of strings separated by spaces instead of commas and without quotes around them.

What does %I mean in Ruby?

The usage of "%I" is just to create hash keys from an array of strings, separated by whitespaces.

How do you convert an array of strings to integers in Ruby?

Converting Strings to Numbers Ruby provides the to_i and to_f methods to convert strings to numbers. to_i converts a string to an integer, and to_f converts a string to a float.


1 Answers

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]
like image 96
Mike S Avatar answered Sep 22 '22 16:09

Mike S