Reputation: 1795
Say I have a class SomeClass with instance variables a and b.
def SomeClass
def initialize a, b
@a = a
@b = b
end
end
When I type into pry the following lines
someclass = SomeClass.new "one", "two"
someclass.instance_variables
As expected it prints an array with symbols
[:@a, :@b]
now, when I use
a.instance_variables.map do |var|
puts var
end
I expect it to print
:@a
:@b
but what I am getting is
@a
@b
Can someone please explain this behaviour ?
Upvotes: 0
Views: 214
Reputation: 361
If you just want to print the symbols as
:@a
:@b
use 'p var', as p calls inspect on its argument unlike puts which calls to_s
Upvotes: 2
Reputation: 121000
puts
transparently calls to_s
on arguments. Symbol#to_s
returns symbol’s name (strings w/out preceding colon.) On the other hand, Array#to_s
calls inspect
on nested elements, that’s why you see colons while putting array’s instance.
Look:
▶ :a.to_s
#=> "a"
▶ [:a,:b,:c].to_s
#=> "[:a, :b, :c]"
This is exactly what you yield calling puts
.
Upvotes: 2