totally
totally

Reputation: 413

added instance variable not shown with inspect in Ruby

Inspect will tell object representation. so I tried this:

animal = "cat"
animal.instance_variable_set(:@a, "dog")
p "inspect object animal: #{animal.inspect}"

But inspect only gave me "cat", I cannot see @a="dog"

If I do this:

puts "instance variables are: #{animal.instance_variables}"

Then I can see [:@a] as output

Why is inspect not giving me everything?

Thanks

Upvotes: 1

Views: 313

Answers (2)

Arup Rakshit
Arup Rakshit

Reputation: 118261

Why is inspect not giving me everything?

DON'T DO THIS -> remove the String#inspect method and see what happen.

class String
  remove_method :inspect
end

animal = "cat"
animal.instance_variable_set(:@a, "dog")
animal # => #<String:0x9976b94 @a=#<String:0x9976b80>>

The above output is what Object#inspect explained -

The default inspect shows the object’s class name, an encoding of the object id, and a list of the instance variables and their values (by calling inspect on each of them).

But, in your case you are calling, String#inspect which is the overridden version of Object#inspect.

Returns a printable version of str, surrounded by quote marks, with special characters escaped.

And your output is what exactly documentation mentioned.

I wanted to give you some in sight. Now don't play like this with Ruby core classes, create your own custom classes, and play with them as much as you can.

Upvotes: 1

Gosha A
Gosha A

Reputation: 4570

String overrides #inspect (String#inspect) to return the original string wrapped in quotes, as opposed to Object#inspect, which dumps everything.

You shouldn't need to re-define String#inspect to account for your special use-case though. If you want your string to have some additional data, you should create your own class instead:

class Animal
  def initialize(name, other)
    @name = name
    @other = other
  end
end

Animal.new("cat", "dog")
# #<Animal:0x007faf9404d828 @name="cat", @other="dog">

Upvotes: 2

Related Questions