过滤任何多个条件的Ruby对象数组?

时间:2015-01-29 21:58:14

标签: ruby-on-rails ruby arrays

如何为满足多个条件的对象过滤Ruby数组?

例如,如果我有一系列博客帖子(每个都有标题,内容和零个或多个标签),并且我的搜索字词为“休假”,我该如何返回所有帖子的列表标题,内容或包含“假期”一词的标签?

显然,以下情况不起作用:

posts.select do |post|
  post.title.include? "vacation"
  post.content.include? "vacation"
  post.tags.include? "vacation"
end

2 个答案:

答案 0 :(得分:0)

您可以尝试以下

posts.select do |post|
  post.title.include? ("vacation") || post.content.include?("vacation") || post.tags
  .include?("vacation")
end

这使用了Ruby ||运算符。

答案 1 :(得分:0)

您可以执行以下操作。

<强>代码

def selected_posts(posts, arr, keyword)
  posts.select { |post| arr.reduce(false) { |present, m|
    present || post.send(m).include?(keyword) } }
end

示例

class Post
  attr_reader :title, :content, :tags
  def initialize(title, content, tags)
    @title   = title
    @content = content
    @tags    = tags
  end
end

posts = [Post.new("a", "b", "vacation"),
         Post.new("a", "b", "c"),
         Post.new("a", "vacation", "vacation")]

arr = [:title, :content, :tags]

selected_posts(posts, arr, "vacation")
  #=> [#<Post:0x007fc87a247da0 @title="a", @content="b", @tags="vacation">,
  #    #<Post:0x007fc87a247a80 @title="a", @content="vacation", @tags="vacation">]