Home > other >  string operation in ruby
string operation in ruby

Time:01-09

I have a below string array object which has 4 elements. I want to compare the elements of this list to an string and want to check if string is part of this list.

list = ["starter_v2", "professional_q", "custom_v", "basic_t9"]
 str = "starter"
if list.include?str #should return true but returning false as it is checking the full string not the substring

Above if condition should return true, however it is returning false.

Can someone suggest me how to fix this, as I am new to ruby and want to compare strings.

For my usecase, in list object I will always have entries with "_" followed by an alphabetic character and I will compare this by string without "_"

CodePudding user response:

Enumerable#include? checks if a given value matches any value in the given enumerable. A substring is not equivalent to a string that contains it, so this check fails.

Instead, you want to check if any string in the array matches your substring. Ruby has handy facilities for this: Enumerable#any? lets you iterate an enumerable, yielding each element to a block, and then will return true if any invocation of the block returns true.

So, you can use:

list.any? {|element| element.include?(str) }

What this will do is check each entry in list to see if str is included in it; once a match is found, it'll stop iterating and return true. If it goes through the entire list without finding a match, it'll return false.

You could also use use element.start_with? if you know that your search string should always match the first part of the string, or you could use a more complex condition which splits each element on underscore and compares the first part, or you could use a regex. The important part is that the block returns true when you want to indicate a match.

  • Related