On Sat, Dec 6, 2014 at 2:46 AM, Jorge C. [email protected] wrote:
Ok. That makes sense. Out of pure curiosity, is there any “hacky” way to
call instance methods in a class context?
You’d first need an instance. Without creating one or passing an
instance on it won’t work.
Here is a way that does what I assume you want
Struct.new(:name).new(“John D.”).tap do |dude|
class << dude
attr_accessor :is_single
end
dude.send :is_single=, true
end
That code is still quite odd (esp. considering your advertised
position) and I would not recommend doing this. There are much
simpler ways to go about things.
Person = Struct.new :name, :is_single
dude = Dudish.new “John D.”, true
There are other approaches, depending on what you want to achieve:
anonymous class
dude = Struct.new(:name, :is_single).new “John D.”, true
anonymous class, other constructor call
dude = Struct.new(:name, :is_single)[“John D.”, true]
not a regular Struct member
Person = Struct.new(:name) do
attr_accessor :is_single
end
dude = Person.new “John D.”
dude.is_single = true
both
dude = Struct.new(:name) do
attr_accessor :is_single
end.new “John D.”
dude.is_single = true
variant
dude = Struct.new(:name) do
attr_accessor :is_single
end.new(“John D.”).tap |o|
o.is_single = true
end
Cheers
robert