如果变量存在于Ruby中,返回变量的方法较短?

Cha*_*ory 1 ruby

这是一个更短,更优雅,更干的方式来写这个在Ruby?

if first_variable
   first_variable # return variable if it exists
else
   second_variable # otherwise, return something else
end
Run Code Online (Sandbox Code Playgroud)

或这个?

if first_variable
   first_variable.method_name 
else
   second_variable
end
Run Code Online (Sandbox Code Playgroud)

Ed *_* S. 16

你的两个例子在语义上是不同的,所以我只举一个例子.

return first_variable || second_variable
Run Code Online (Sandbox Code Playgroud)

如果first_variable不是nil,则第二个示例返回方法调用的结果.这与你的第一个例子不同,所以我不明白比较它们.我也不明白你对DRY的使用.在任何一种情况下,你都不会重复自己.为什么if语句会这么烦你?这不是你应该担心的事情.