In Ruby, how can I initialize instance variables in new objects of core classes created from literal

Posted by Ollie Saunders on Stack Overflow See other posts from Stack Overflow or by Ollie Saunders
Published on 2009-05-27T09:26:29Z Indexed on 2010/04/22 0:53 UTC
Read the original article Hit count: 274

Filed under:
|
class Object
  attr_reader :foo
  def initialize
    @foo = 'bar'
  end
end

Object.new.foo # => 'bar'
''.foo # => nil
//.foo # => nil
[].foo # => nil

I want them all to return 'bar'

Am aware that you can do this already:

class Object
  def foo
    'bar'
  end
end

But I specifically want to initialize a state variable. Also note that this doesn't work.

class String
  alias_method :old_init, :initialize
  def initialize(*args)
    super
    old_init(*args)
  end
end

class Object
  attr_reader :foo
  def initialize
    @foo = 'bar'
    super
  end
end

''.foo # => nil

Nor does this:

class String
  attr_reader :foo
  def initialize
    @foo = 'bar'
  end
end

''.instance_variables # => []

I'm beginning to think that this isn't actually possible.

© Stack Overflow or respective owner

Related posts about ruby

Related posts about oop