对于变量的多次检查比if语句更好的数据结构?

时间:2010-09-16 11:09:37

标签: ruby-on-rails ruby data-structures

所以,我有这段代码,是的,它看起来很难看。有没有更好的数据结构我可以用来比较row.add,row.modify,row.delete和row.query与“Y”并调用get_role函数?请注意,此代码块在循环中运行,因此是“行”。

    if row.add == "y"
      role_ids << get_role("c")  
    end
    if row.modify == "y"
      role_ids << get_role("u")
    end
    if row.delete == "y"
      role_ids << get_role("d")
    end
    if row.query == "y"
      role_ids << get_role("r")
    end

谢谢!

3 个答案:

答案 0 :(得分:2)

role_ids << case
  when row.add    == "y" then get_role("c")
  when row.modify == "y" then get_role("u")
  when row.delete == "y" then get_role("d")
  when row.query  == "y" then get_role("r")
end

答案 1 :(得分:2)

operations = { :add => "c", :modify => "u", :delete => "d", :query => "r" }
operations.each do |key,value|
  role_ids << get_role(value) if row.send(key) == "y"
end

答案 2 :(得分:-1)

更新!

更改为

operations = [row.add,row.modify,row.delete,row.query]
crud=["c","u","d","r"]
operations.each_with_index{|operation,i| if operation == "y" then role_ids << get_role(crud[i]) end}