[英]How to select a string that fits in the array then convert to string in Ruby?
I am trying to select a specific item that has a word 'Test'
in it from an array using Ruby.我正在尝试使用 Ruby 从数组中 select 一个特定项目,其中包含
'Test'
一词。 The output will then be converted to a string.然后 output 将被转换为字符串。 Can someone tell me what have I missed?
有人能告诉我我错过了什么吗?
Script脚本
a = ['bTest', 'val', 'Ten']
a.select{ |o| o.include? 'Test' }.to_s
Output Output
["bTest"]
My expected output我的预期 output
'bTest'
Thank you.谢谢你。
.select
will select all items from an array for which the block is true. .select
将 select 数组中的所有项目,该块为真。 If you only want to select one item, then use .detect
or .find
(which are aliases):如果您只想 select 一项,则使用
.detect
或.find
(它们是别名):
a = ['bTest', 'val', 'Ten']
a.detect { |o| o.include? 'Test' }.to_s
# => "bTest"
If you just want to display the result:如果您只想显示结果:
a = ['bTest', 'val', 'Ten']
puts a.select{|o| o.include? 'Test' }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.