0
How can I make a list or hash from user's input in Ruby?
For example: I want to make list like this: list = [1, 2, 3], but I want to put 1, 2, and 3 from user's input. User will write something like this: 1, 2, 3; and Ruby will put the numbers to list. How to do it?
5 Réponses
+ 9
You can do something like this
i = gets.chomp.split(',')
arr = []
i.each do |x|
arr << x.to_i
end
print arr
+ 3
Code snippet tip : you don't even need to force the user to use commas
list = gets.split.map(&:to_i)
+ 3
Mert Yazıcı perfect code, but not real ruby style eh 😉
+ 3
lol bedawang
+ 2
Or a simpler ones.
list = gets.split(',').map(&:to_i)