views:

66

answers:

5

I remember coming across this when first watching some Ruby videos, but I can't find it again. When Ruby shows something like this:

#<Role:0x11157b630>  

,what is going on?

I have three roles (admin/staff/client) and I would like to show one of these, not

#<Role:0x11157b630>.

Any idea how I could do that?

Cheers!

+5  A: 

What you're seeing is just a representation of the instance you've got. Say you have a title attribute on the class Role, you could, instead of logger.debug @role do something like logger.debug @role.title. If you want just doing logger.debug @role to print out something more useful, define a to_s method on Role.

thenduks
+2  A: 

Appending an inspect method should show some more details.

@role.inspect
dombesz
Thanks! With inspect I get [#<Role id: 1, name: "admin">] and [#<Role id: 2, name: "staff">] and [#<Role id: 3, name: "client">]. When I do something like user.roles.name I get "Role".
dombesz
A: 

When I started with rails I had strange bugs sometimes when I made something simple like:

<% @posts.each do |post| %>
  ....
<% end %> 

I would get those strange outputs under the list of posts.

For example:

#<Post:0x11157b630>#<Post:0x11157b630>#<Post:0x11157b630>

Turns out I accidentally put a "=" in there before the loop.

<%= @posts.each do |post| %>
      ....
<% end %> 
Staffan Jonsson
A: 

That's what the default implementation of to_s looks like; class name followed by memory location. You can define your own version if you like:

def to_s
   "My name is #{@name}"
end
Douglas
A: 

According to The Secret of Object#to_s, the number in #<Role:0x11157b630> is double the object's object_id in hexidecimal.

Andrew Grimm