查找值Hash类似于LIKE sql(Ruby)

时间:2013-03-15 15:30:47

标签: ruby-on-rails ruby ruby-on-rails-3

如何在哈希中搜索类似于SQL LIKE的值?

示例:

[ {:x=>"Hello"},{:x=>"Hello 1"]]

我希望搜索所有值包含'他'。

2 个答案:

答案 0 :(得分:4)

include

a.select{|e| e[:x].include?('he')}

或使用正则表达式match

a.select{|e| e[:x] =~ /he/}

答案 1 :(得分:2)

haystack = [{:x=>"Hello"}, {:x=>"Hello 1"}, {:x=>"Goodbye"}]

haystack.find_all do |entry|
  entry[:x] =~ /he/i # /i makes it case insensitive
end

#=> [{:x=>"Hello"}, {:x=>"Hello 1"}]