从字符串中获取值

时间:2015-03-09 18:52:40

标签: ruby

我正在尝试匹配字符串(str)中的一个或多个关键字,但我没有运气。我的方法是在我只需匹配任何一个(一个或多个)时尝试匹配所有键。

@str = "g stands for girl and b is for boy"

def key1
 %w[a, b, c, d, f, g]
end    

def result
 if @str.include?( key1 )
  puts "happy days"
 else
  puts "bad days"
 end
end

puts result # => bad days

如何让它显示“快乐的日子”?

PS:我不知道该怎么命名。也许一个mod可以重命名它?

3 个答案:

答案 0 :(得分:3)

你问你的字符串是否包含数组:["a", "b", "c", "d", "f", "g"]

我认为你想要问的是:数组中是否还存在字符串中的任何元素?这是Enumerable#any的一个很好的用例:

[2] pry(main)> @str = "g stands for girl and b is for boy"
=> "g stands for girl and b is for boy"
[3] key1 = %w[a b c d f g]
=> ["a", "b", "c", "d", "f", "g"]
[4] pry(main)> key1.any? { |letter| @str.include?(letter) }
=> true

因此要重构代码,它可能如下所示:

@str = "g stands for girl and b is for boy"

def key1
 %w[a b c d f g]
end    

def result
 if key1.any? { |letter| @str.include?(letter) }
  puts "happy days"
 else
  puts "bad days"
 end
end

需要注意的是,%w你不需要使用逗号,你可以简单地用空格分隔字母(如上所述)。

答案 1 :(得分:1)

我无法清楚地理解您的问题,但我怀疑您正在寻找以下内容:

key1.find { |k| @str.include? k }

答案 2 :(得分:1)

我会使用正则表达式:

MAGIC_CHARS = %w[a b c d f g]
  #=> ["a", "b", "c", "d", "f", "g"]

def result(str)
  (str =~ /#{MAGIC_CHARS.join('|')}/) ? "happy days" : "bad days"
end

result("g stands for girl and b is for boy")
  #=> "happy days" 
result("nothin' here")
  #=> "bad days" 

注意:

/#{MAGIC_CHARS.join('|')}/
  #=> /a|b|c|d|f|g/ 

你可以写一下:

Regexp.union(MAGIC_CHARS.map { |c| /c/ })
  #=> /(?-mix:c)|(?-mix:c)|(?-mix:c)|(?-mix:c)|(?-mix:c)|(?-mix:c)/

/[#{MAGIC_CHARS.join('')}]/
  #=> /[abcdfg]/ 

另一种方式:

def result(str)
  (str.chars & MAGIC_CHARS).any? ? "happy days" : "bad days"
end

result("g stands for girl and b is for boy")
  #=> "happy days" 
result("nothin' here")
  #=> "bad days" 
相关问题