Closed tan-wei closed 4 years ago
Trivial and (possibly) elegant, yes. Safe, no.
This approach will cause problems if there are fields in different nested structures with the same name.
a = A.new
a.flat_assign(:a => 1, :b => 2, :d => 3)
class BinData::Struct
def flat_assign(val)
assign(val)
unassigned = val.keep_if { |k,v| ! field_names.include? k }
field_names.each do |field|
self[field].flat_assign(unassigned) rescue NoMethodError
end
end
end
Got it. Maybe provide a templated assign maybe a more safe solution. Yes, I've think of sometinng just like flat_assign
, it requries every names in every nested stuctures have different names in order to set their values in the corrent
location. But in many cases, different names for all is not an elegent solution...
Thanks very much.
Firstly, thanks for the great tool to parse messages. It works quite well and elegant when parsing a structured message. Maybe the most powerful tool in all programming languages, after I've tried dozens of tools to parse message.
But I have a question about the object assignment. For example:
If we want to create a new A with assign
a
,b
, andd
, according to the documents and examples (compared to parsing process, assignment process is less mentioned), we can do it like this:It works well. However, for a complex object, is there a trival way to assign a valid object? A workaround may be done like this:
But I don't know whether there is a trival and elegant one. Thanks!