Mahesh Mesta
Mahesh Mesta

Reputation: 169

Print array numerals on a single line in ruby console

a = [1, 2, 3, 5, 7]

I want to print on ruby console 1 2 3 5 7

I tried this

a.each{|i| puts i.join(" ")}

it throws this error

 undefined method `join' for 1: Fixnum

I tried converting each element to string and then print them

    m = a.map {|l| l.to_s}

then

    m.each{|i| puts i.join(" ")}

it still throws an error

   undefined method `join' for "1": String

How do I achieve the desired result

Upvotes: 0

Views: 367

Answers (2)

Sagar Pandya
Sagar Pandya

Reputation: 9497

Since the other answer isn't what you want, try this:

a.each_with_index { |n, i| print i == a.size - 1 ? "#{n}\n" : "#{n} " }

Upvotes: 1

jvillian
jvillian

Reputation: 20263

You're close. Try this one:

2.3.1 :002 > puts [1,2,3,5,7].join(' ')
 1 2 3 5 7

Upvotes: 2

Related Questions