如何 select 适合数组的字符串然后转换为 Ruby 中的字符串?

How to select a string that fits in the array then convert to string in Ruby?

我正在尝试 select 使用 Ruby 从数组中包含单词 'Test' 的特定项目。然后输出将被转换为字符串。谁能告诉我我错过了什么?

脚本

a = ['bTest', 'val', 'Ten']
a.select{ |o| o.include? 'Test' }.to_s

输出

["bTest"]

我的预期输出

'bTest'

谢谢。

.select 将 select 数组中块为真的所有项目。如果您只想 select 一项,则使用 .detect.find (它们是别名):

a = ['bTest', 'val', 'Ten']
a.detect { |o| o.include? 'Test' }.to_s
# => "bTest"

如果只想显示结果:

a = ['bTest', 'val', 'Ten']
puts a.select{|o| o.include? 'Test' }