简体   繁体   English

在ruby控制台的一行中打印数组数字

[英]Print array numerals on a single line in ruby console

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

I want to print on ruby console 1 2 3 5 7 我想在红宝石控制台上打印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 如何取得理想的结果

You're close. 你近了 Try this one: 试试这个:

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

由于其他答案不是您想要的,请尝试以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM