but that doesn’t work. I could maybe force it to work by manually
creating setter methods, but that’s not an elegant solution either, I’d
rather have the occassional use of instance_variable_set than craft
setters.
but that doesn’t work. I could maybe force it to work by manually
creating setter methods, but that’s not an elegant solution either, I’d
rather have the occassional use of instance_variable_set than craft
setters.
In another language I used, I could simply do the equivalent of
myobject.iname = ivalue
This breaks the encapsulation that objects are supposed to provide for
their
hidden state. I have to say I like the fact that
instance_variable_get/instance_variable_set are long and unwieldy. By
using
them you hopefully remind yourself that you’re doing something naughty
by
touching an object’s private parts.
I was hoping in Ruby that at least this was possible:
but that doesn’t work. I could maybe force it to work by manually
creating setter methods, but that’s not an elegant solution either, I’d
rather have the occassional use of instance_variable_set than craft
setters.
It’s Ruby, a lot is possible! You could add some method_missing magic
so:
You’re confusing methods and variables. They’re not the same, but you’re
on the right track with the code above, but you’d be calling the getter,
not the setter. Check it:
class X
attr_accessor :x # creates x and x= methods
end
You’re confusing methods and variables. They’re not the same, but you’re
on the right track with the code above, but you’d be calling the getter,
not the setter. Check it:
class X
attr_accessor :x # creates x and x= methods
end
o = X.new
o.send(“x=”, 42)
p x
I wasn’t confusing them, I was hoping Ruby’s send would be flexible
enough to work with both of them (in conjunction with the accessors
being defined). What I didn’t think of in this context was Ruby’s x=
being considered the setter method and not just x, which I knew, and
should have recognized – so yep, that was the ticket. You win!
Sorry, no prizes
on the right track with the code above, but you’d be calling the getter,
I wasn’t confusing them, I was hoping Ruby’s send would be flexible
enough to work with both of them (in conjunction with the accessors
being defined). What I didn’t think of in this context was Ruby’s x=
being considered the setter method and not just x, which I knew, and
should have recognized – so yep, that was the ticket. You win!
Sorry, no prizes
Here are two other approaches using widely underused class Struct and
that differ in the way they deal with values not present in the Hash:
Shape = Struct.new :size, :fill_color, :line_color, :line_width do
def self.from_hash_1(h)
sh = new
h.each {|k,v| sh[k] = v}
sh
end
def self.from_hash_2(h)
sh = new
members.each {|m| sh[m] = h[m]}
sh
end
end