Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print contents of array in oneline

Tags:

arrays

ruby

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==1i 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.

like image 542
pratik watwani Avatar asked Dec 05 '22 19:12

pratik watwani


1 Answers

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.

like image 68
tckmn Avatar answered Jan 04 '23 21:01

tckmn