Ruby Class Return Value

2020-07-27 20:43发布

I'm learning Ruby and made a class to help:

class WhatImDoing
    def initialize
        puts "not doing anything"
    end
end

with the output of:

not doing anything
#<WhatImDoing:0xb74b14e8>

I'm curious, what is the second line all about? Is it a reference location for the WhatImDoing object I created? Can I access objects through this location(like a pointer or something)? Etc... Just trying to get a better understanding of Ruby, in general.

Thanks.

标签: ruby
3条回答
smile是对你的礼貌
2楼-- · 2020-07-27 21:07

Yes, it is reference to the object you are creating. Yes, you can access that object.

查看更多
够拽才男人
3楼-- · 2020-07-27 21:26

The second line is the output of irb, showing the return value of the last statement.

If you set something equal to that value:

> class WhatImDoing
    def initialize
      puts "not doing anything"
    end

    def ohai
      puts "Ohai"
    end
  end
> tmp = WhatImDoing.new
=> #<WhatImDoing:0x5cd5a2a9>

You could use it:

> tmp.ohai
Ohai

If you had a custom to_s it would show that instead:

> class WhatImDoing
    def to_s
      "#{super} kthxbai"
    end
  endt
> tmp = WhatImDoing.new
=> #<WhatImDoing:0x3e389405> kthxbai 
查看更多
萌系小妹纸
4楼-- · 2020-07-27 21:30

I'm assuming that was the output of irb. Irb tried to print your object, i.e. convert it to a string. Since you didn't provide a custom to_s ("to string") method, your object inherited this one:

http://ruby-doc.org/core-1.9.3/Object.html#method-i-to_s

Returns a string representing obj. The default to_s prints the object’s class and an encoding of the object id. As a special case, the top-level object that is the initial execution context of Ruby programs returns “main.”

Further digging into the source code reveals that the hexadecimal number is, indeed, the memory address occupied by that object instance. There isn't really anything fancy you can do with that information, in Ruby. It's just a convenient way to generate an unique identifier for an object instance.

查看更多
登录 后发表回答