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 :)
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.
The usage of "%I" is just to create hash keys from an array of strings, separated by whitespaces.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With