【问题标题】:Ruby using params to implement optional function callRuby 使用 params 实现可选函数调用
【发布时间】:2015-11-28 03:06:14
【问题描述】:

我需要一个函数来根据检查它们是否满足一些判断来获取一些东西,判断是一些需要参数的函数。如:

Something.is_close_to?(:sky)

我已经根据我在here 中学到的内容制作了一个。

def get_somethings(options = {})
  somethings = []
  Something.all.each do |something|
    this_is_it = true

    options.each_pair do |key, value|
      expected_result = value.pop
      this_is_it = false if !(Something.first.send(key, *value) == expected_result)
    end

    somethings << something if this_is_it
  end
  return somethings
end

我可以通过这样的方式调用这个函数:

options = {is_close_to?: ["sky", true], is_higher_than?: [2000, true]}
get_somethings()

我认为我的方式是扭曲的,所以我想知道是否有更好的方法来做到这一点。

【问题讨论】:

  • 抱歉打错了,最后一行代码是:get_somethings(options)
  • 我投票结束这个问题,因为它是关于如何更好地构建工作代码的。这对 SO 来说不是一个好话题。不过,对于codereview.stackexchange.com 来说,这可能是个好问题

标签: ruby-on-rails ruby


【解决方案1】:

让我们把它分成几个步骤:

  1. 从集合中选择符合条件的项目
  2. 匹配您的条件中的所有条件
  3. 从哈希中提取元素(称为解构)
  4. 在对象上调用检查方法

代码

def get_somethings(collection, conditions = {})
  # Step 1
  collection.find_all do |item|
    matches_conditions item, conditions
  end
end

# Step 2
def matches_conditions(item, conditions)
  # Step 2           Step 3
  conditions.all? do |predicate, (argument, expected)|
    # Step 4
    item.public_send(predicate, argument) == expected
  end
end

conditions = {is_close_to?: ["sky", true], is_higher_than?: [2000, true]}
get_somethings(Something.all, conditions)

【讨论】:

  • 谢谢,我会把它分成两部分,但我认为不应该使用:conditions.all? do |predicate, (argument, expected)|这里,如果这里有多个参数怎么办?如:conditions = {is_height_between?: [100, 200, true]} |谓词,(参数,预期)|无法拆分 [100, 200]
【解决方案2】:

有问题的代码有错误,抱歉,工作版本应该是这样的:

def get_somethings(options = {})
  somethings = []
  Something.all.each do |something|
    found_one = true
    options.each_pair do |key, value|
      expected_result = value.first

      if something.send(key, *value.drop(1)) != expected_result
        found_one = false
      end

    end
    somethings << something if found_one
  end
  return somethings
end

【讨论】:

  • 您好,欢迎来到 SO!关于您上面的问题,有一个名为“编辑”的链接。单击该链接将允许您编辑问题以修正错误或以其他方式改进问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多