class User
def initialize(name)
@name = name
end
def get_name
@name
end
end
:get_name
obj = User.new(‘Raj’)
#<User:0x000056458c0283e8 @name=“Raj”>
obj
#<User:0x000056458c0283e8 @name=“Raj”>
obj.inspect
“#<User:0x000056458c0283e8 @name="Raj">”
p obj
#<User:0x000056458c0283e8 @name=“Raj”>
#<User:0x000056458c0283e8 @name=“Raj”>
puts obj
#User:0x000056458c0283e8
p obj print same thing two times, Why?
My Ruby version is:
ruby -v
ruby 2.5.0p0 (2017-12-25 revision 61468) [x86_64-linux]
I assume you trying it in IRB. IRBs logic is to:
-
perform the command
-
print what that command returned
As p
method returns its argument: http://ruby-doc.org/core-2.2.0/Kernel.html#method-i-p — you get this:
p obj
#<User:0x000056458c0283e8 @name=“Raj”> — that’s p
working, outputing the object
#<User:0x000056458c0283e8 @name=“Raj”> — that’s p
method returned.
For puts
, you don’t see the second line, because puts
returns nothing: http://ruby-doc.org/core-2.2.0/Kernel.html#method-i-puts
···
2018-02-24 12:23 GMT+02:00 Raj Kumar Sharma raj4057kumar@gmail.com:
class User
def initialize(name)
@name = name
end
def get_name
@name
end
end
:get_name
obj = User.new(‘Raj’)
#<User:0x000056458c0283e8 @name=“Raj”>
obj
#<User:0x000056458c0283e8 @name=“Raj”>
obj.inspect
“#<User:0x000056458c0283e8 @name="Raj">”
p obj
#<User:0x000056458c0283e8 @name=“Raj”>
#<User:0x000056458c0283e8 @name=“Raj”>
puts obj
#User:0x000056458c0283e8
p obj print same thing two times, Why?
My Ruby version is:
ruby -v
ruby 2.5.0p0 (2017-12-25 revision 61468) [x86_64-linux]
Unsubscribe: mailto:ruby-talk-request@ruby-lang.org?subject=unsubscribe
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk>