0

I have a little program accepting user input of multiple integers separated by whitespace, ex: 4 5 6 7

I then push this into an array and want to find the class of each element in the array, which I expect to be a string since I am using the gets command. I am using the .each iterator to do this, but in my code below when I puts output.class I get one output of array instead of four outputs of string.

Can someone point out what I am doing wrong here?

values = []

puts "enter segment values separated by spaces: "
entry = gets.split
values << entry


values.each do |output|
    puts output.class
end
0

1 Answer 1

2

entry is an array, and hence, values array contains only one element which happens to be entry array.

To fix the issue, you can replace values << entry with:

values.push *entry

Explanation

Array#<< method pushes a single object into the array. In your case, you were pushing entry array, hence, it got pushed as single element.

If you want to push each individual element of entry array, then, use of splat operator (*) will allow us to convert an array into multiple arguments to a method. Unfortunately, << takes single argument, and will error out if we do:

values << *entry
#=> main.rb:5: syntax error, unexpected *
#    values << *entry
               ^

There is another method, Array#push, which can be passed variable number of objects and it will push each one into the array. So, final code will look like:

values.push *entry
Sign up to request clarification or add additional context in comments.

5 Comments

Your suggestion is correct, but there is no need to change << into push at the same time. That is confusing.
@sawa - It gives me an error (syntax error, unexpected *) when I do values << *entry, so I tried push
I see. But you better explain that.
Thank you both for your help :)
Alternatively, you can do values.concat(entry).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.