Reputation: 137
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.
Upvotes: 6
Views: 19527
Reputation: 121
New to Ruby as well! I just tried:
puts "#{array.inspect}"
where array = [2 3 4 5 6 77 88]
. It resulted in:
["2", "3", "4", "5", "6", "77", "88"]
which is a single line printout, if a quick fix is needed. But array.join(' ')
is much better.
Upvotes: 2
Reputation: 9497
Instead of puts array
try p array
if you want the whole array printed to screen.
Upvotes: 3
Reputation: 59273
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.
Upvotes: 15