关于什么更符合红宝石标准的快速问题.
例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?
如果使用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)