Michael Fellinger
1/9/2008 5:38:00 AM
On Jan 9, 2008 2:02 PM, Giles Bowkett <gilesb@gmail.com> wrote:
> I have some code which uses Structs. I'd rather use keyword args. I'm
> generating data objects to store MIDI note data, and it's kind of
> hideously unreadable:
>
> Note.new(2, 43, 0.25, 127, now += interval)
>
> This would be much nicer:
>
> Note.new(:channel => 2,
> :note => 43,
> :duration => 0.25,
> :velocity => 127,
> :time => now += interval)
>
> (God I wish I could configure bloody Gmail to use monospaced fonts.)
>
> Anyway, is there an easy equivalent to Struct which, instead of taking
> stuff in sequence, takes a Hash of options, in a Rails-y style? Like a
> HashStruct? Does Facets have such a thing, maybe haps? If not, is the
> basic code for Struct in Ruby, and/or is a class like Struct but with
> Hashes easy to build?
One possibility, method for Note only:
manveru@pi ~ % irb
class Note < Struct.new(:channel, :note, :duration, :velocity, :time)
def self.create(hash)
new(*hash.values_at(*members.map{|m| m.to_sym}))
end
end
# nil
Note.create(:channel => 1, :note => 2, :duration => 3, :velocity => 3,
:time => Time.now)
# #<struct Note channel=1, note=2, duration=3, velocity=3, time=Wed
Jan 09 14:36:21 +0900 2008>
Second one, method for all Structs:
manveru@pi ~ % irb
class Struct
def self.create(hash)
new(*hash.values_at(*members.map{|m| m.to_sym}))
end
end
# nil
Note = Struct.new(:channel, :note, :duration, :velocity, :time)
# Note
Note.create(:channel => 1, :note => 2, :duration => 3, :velocity => 3,
:time => Time.now)
# #<struct Note channel=1, note=2, duration=3, velocity=3, time=Wed
Jan 09 14:37:20 +0900 2008>