Search code examples
arraysrubystringscriptingdata-conversion

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. The output will then be converted to a string. Can someone tell me what have I missed?

Script

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

Output

["bTest"]

My expected output

'bTest'

Thank you.


Solution

  • .select will select all items from an array for which the block is true. If you only want to select one item, then use .detect or .find (which are aliases):

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