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 Doe").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 Doe", true
There are other approaches, depending on what you want to achieve:
# anonymous class
dude = Struct.new(:name, :is_single).new "John Doe", true
# anonymous class, other constructor call
dude = Struct.new(:name, :is_single)["John Doe", true]
# not a regular Struct member
Person = Struct.new(:name) do
attr_accessor :is_single
end
dude = Person.new "John Doe"
dude.is_single = true
# both
dude = Struct.new(:name) do
attr_accessor :is_single
end.new "John Doe"
dude.is_single = true
# variant
dude = Struct.new(:name) do
attr_accessor :is_single
end.new("John Doe").tap |o|
o.is_single = true
end
Cheers
robert
···
On Sat, Dec 6, 2014 at 2:46 AM, Jorge Colon <2upmedia@gmail.com> wrote:
Ok. That makes sense. Out of pure curiosity, is there any "hacky" way to
call instance methods in a class context?
--
[guy, jim].each {|him| remember.him do |as, often| as.you_can - without end}
http://blog.rubybestpractices.com/