[英]how to assign in ruby without checking each step if the values you assign exist
Unfortunately I couldn't think of a really good way to write this question, we have a lot of code that ends up looking like this:不幸的是,我想不出一个很好的方法来写这个问题,我们有很多代码最终看起来像这样:
@annotation.note = params[:annotation][:note] if params[:annotation][:note]
@annotation.style = params[:annotation][:style] if params[:annotation][:style]
I find that if params at the end check annoying.我发现 if params 最后检查很烦人。
So is there a way to write this more succinctly, so that it is understood that the value only gets copied over if it exists without having to ask that explicit if at the end each time?那么有没有办法更简洁地写这个,以便理解该值只有在它存在时才会被复制,而不必每次都明确询问是否在最后?
x = params[:annotation][:note] and @annotation.note = x
x = params[:annotation][:style] and @annotation.style = x
You could easily extract the checks into a method, so that your code is more DRY.您可以轻松地将检查提取到一个方法中,以便您的代码更加 DRY。 Like this, for example:像这样,例如:
def copy obj, prop, params
val = params[prop]
obj.send "#{prop}=", val if val
end
ann = params[:annotation]
copy @annotation, :node, ann
copy @annotation, :style, ann
you can also try this:你也可以试试这个:
params[:annotation].each_pair {|k,v| v && @annotation.send("#{k}=", v) }
some tests:一些测试:
require 'ostruct'
@annotation = OpenStruct.new
params = {:annotation => {:note => 'note', :style => 'style'}}
params[:annotation].each_pair {|k,v| v && @annotation.send("#{k}=", v) }
p @annotation
#<OpenStruct note="note", style="style">
@annotation = OpenStruct.new
params = {:annotation => {:note => nil, :style => 'style'}}
params[:annotation].each_pair {|k,v| v && @annotation.send("#{k}=", v) }
p @annotation
#<OpenStruct style="style">
@annotation = OpenStruct.new
params = {:annotation => {:note => 'note'}}
params[:annotation].each_pair {|k,v| v && @annotation.send("#{k}=", v) }
p @annotation
#<OpenStruct note="note">
params[:annotation][:note].tap{|v| @annotation.note = v if v}
params[:annotation][:style].tap{|v| @annotation.style = v if v}
Here's another method as well:这里还有另一种方法:
@annotation.note = params[:annotation][:note] || @annotation.note
I'll admit, you do repeat @annotation.note
but the statement length is still reduced.我承认,您确实重复了@annotation.note
但语句长度仍然减少了。
Here's another attempt:这是另一个尝试:
@annotation.note = params[:annotation][:note] rescue nil
@annotation.note will remain nil
if params[:annotation][:note]
does not exist.如果params[:annotation][:note]
不存在,@annotation.note 将保持nil
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.