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?

3rd Jan 2019, 3:03 PM
Teodore
5 Respostas
+ 9
You can do something like this i = gets.chomp.split(',') arr = [] i.each do |x| arr << x.to_i end print arr
3rd Jan 2019, 3:16 PM
Mert Yazıcı
Mert Yazıcı - avatar
+ 3
Code snippet tip : you don't even need to force the user to use commas list = gets.split.map(&:to_i)
3rd Jan 2019, 11:35 PM
bedawang
bedawang - avatar
+ 3
Mert Yazıcı perfect code, but not real ruby style eh 😉
3rd Jan 2019, 11:42 PM
bedawang
bedawang - avatar
+ 3
3rd Jan 2019, 11:48 PM
ShortCode
+ 2
Or a simpler ones. list = gets.split(',').map(&:to_i)
3rd Jan 2019, 11:02 PM
ShortCode