My approach
- get array elements as string with delimiter such as space or comma
- split the string
- Convert each element into number and push into the array
The code looks like this:
puts 'Enter array elements with a space'
array_as_string = gets
if array_as_string.length > 0
input_array = []
array_as_string.split(' ').each { |x| input_array.push(x.to_i) }
else
puts 'Invalid input'
end
Is there a better/ efficient alternative or a straight forward way of doing this?
The default argument for
splitis whitespace.The idiom to do
something with every element in an array and get an array as result
is
map.