Ruby中的字符串操作

huangapple go评论69阅读模式
英文:

string operation in ruby

问题

我有一个下面的字符串数组对象,其中包含4个元素。我想要将这个列表的元素与一个字符串进行比较,并检查字符串是否是这个列表的一部分。

  1. list = ["starter_v2", "professional_q", "custom_v", "basic_t9"]
  2. str = "starter"
  3. if list.any? { |item| item.include?(str) }
  4. # 应该返回true,但返回false,因为它检查的是整个字符串而不是子字符串
  5. puts "true"
  6. else
  7. puts "false"
  8. end

上面的条件应该返回true,但实际上返回false。

有人可以建议我如何修复这个问题吗?因为我是Ruby的新手,想要比较字符串。

对于我的用例,列表对象中的条目将始终以“”后跟字母字符的形式存在,我将通过字符串进行比较,而不包括“”。

英文:

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.

  1. list = ["starter_v2", "professional_q", "custom_v", "basic_t9"]
  2. str = "starter"
  3. 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 "_"

答案1

得分: 1

Enumerable#include?检查给定的值是否与给定的可枚举值中的任何值匹配。子串与包含它的字符串不等效,因此此检查失败。

相反,您想要检查数组中的任何字符串是否与您的子串匹配。Ruby 为此提供了方便的工具:Enumerable#any?允许您迭代一个可枚举对象,将每个元素传递给一个块,然后如果块的任何调用返回 true,则返回 true。

所以,您可以使用:

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

这将检查list中的每个条目,以查看是否包含str;一旦找到匹配项,它将停止迭代并返回 true。如果在遍历整个列表时找不到匹配项,它将返回 false。

您还可以使用element.start_with?,如果您知道您的搜索字符串应始终与字符串的第一部分匹配,或者您可以使用更复杂的条件,将每个元素拆分为下划线并比较第一部分,或者您可以使用正则表达式。重要的是当您想指示匹配时块返回 true。

英文:

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:

  1. 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.

huangapple
  • 本文由 发表于 2023年1月9日 13:22:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/75053451.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定