【问题标题】:How do you print out one element from a two element list, while retaining brackets and quotes?如何从两个元素列表中打印出一个元素,同时保留括号和引号?
【发布时间】:2026-01-19 15:50:02
【问题描述】:

这里是列表:

[ [ "First", "A" ], [ "Second", "B" ] ]

我现在正在使用:

"#{list[0]} is the first element"

返回:

"firsta is the first element"

我希望它返回:

["First", "A"] is the first element

完整代码:

set1 = list[0].last.downcase
set2 = list[1].last.downcase
if set1.eql?(set2)
   "#{list[0]} is the first element"
elseif
   #to-do
else
   #to-do
end

另外,我正在使用来自 labs.codecademy.com (Ruby 1.8.7) 的在线解释器。

【问题讨论】:

  • 你能发布完整的程序代码吗?我正在 IRB 中尝试这个,它给了我想要的结果,我不确定你是如何看待“firsta 是第一个元素”。
  • 我想他正在使用 ruby​​ 1.8

标签: ruby-on-rails ruby arrays multidimensional-array


【解决方案1】:

您使用的是 Ruby 1.8,并且看到的是 1.8 版本的 Array#to_s

to_s → 字符串

返回self.join

[ "a", "e", "i", "o" ].to_s   #=> "aeio"

使用 Ruby 1.9 会得到你期望的输出:

to_s()

别名:inspect

但您可以在 1.8 中自己使用 inspect

1.8.7 >> list = [ [ "First", "A" ], [ "Second", "B" ] ]
=> [["First", "A"], ["Second", "B"]]
1.8.7 >> list[0].to_s
=> "FirstA"
1.8.7 >> "#{list[0].inspect} is the first element"
=> "["First", "A"] is the first element"

【讨论】: