Ruby社区意见:多个或声明还是单个包含?

Dan*_*ahn 2 ruby coding-style

关于什么更符合红宝石标准的快速问题.

例1:(a)或(b)更好吗?

# A
annoying_at_times if user == 'Draper' || user == 'Olson' || user == 'Sterling'

# B
annoying_at_times if ['Draper', 'Olson', 'Sterling'].include? user
Run Code Online (Sandbox Code Playgroud)

例2:(c)或(d)更好吗?

# C
i_freaking_love if user == 'Harris' || user == 'Pryce'

# D
i_freaking_love if ['Harris', 'Pryce'].include? user
Run Code Online (Sandbox Code Playgroud)

或者这样做会很疯狂吗?

class Object
   def is_in?(array)
     array.include?(self)
   end
end

#Usage
founding_partner if user.is_in? ['Sterling', 'Cooper', 'Draper', 'Pryce']
Run Code Online (Sandbox Code Playgroud)

编辑

如果is_in?是一种方法User而不是Object

Lit*_*mus 8

如果使用rails(或仅active_support使用核心扩展樱桃采摘),开箱即用的另一个有趣的变体.这与你的相似is_in?.

require 'active_support'
require 'active_support/core_ext/object/inclusion'
Run Code Online (Sandbox Code Playgroud)

然后

user.in? ['Harris', 'Pryce']
Run Code Online (Sandbox Code Playgroud)

  • "只需要积极的支持也足够了".啊.不要那样对待别人.使用[核心扩展](http://edgeguides.rubyonrails.org/active_support_core_extensions.html)并仅选择所需的例程:[`in?`](http://edgeguides.rubyonrails.org/active_support_core_extensions.html#在-问号) (2认同)