I am new to ruby and was trying out with arrays.i want to print the array in single line. this is the block of code(please ignore any errors)
array=[]
puts "Choose an option: ","1.Push, 2.Pop, 3.Display Length"
choice=gets.to_i
while choice!=4
if choice==1
puts "enter Number of elements to be pushed"
n=gets.to_i
n.times do
puts "Enter element"
el=gets.to_s
array.push el
end
puts array
elsif choice==2
puts array.pop
elsif choice==3
puts array.length
else
puts "invalid"
end
end
when I print my array in if choice==1
i get all the outputs on different lines,
example
hello
i
am
beginner
to
ruby
is there anyway to put the output in single line?
i.e hello i am beginner to ruby
EDIT: I have even tried using puts array.join(' ')
, but that too doesnt work.
First of all,
puts array
should be
puts array.join(' ')
By default, puts
outputs each element on its own line.
Secondly,
el=gets.to_s
should be
el = gets.chomp
gets
returns a string, so there's not much point in converting a string to a string. But the string returned by gets
will also end with a newline, so you need to chomp
that newline off.
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