Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - What happens when I convert an object into string?

I was playing with Rails Console. By chance, I accidentally convert an object into a string. Below are my codes.

Rails Console

user = User.find(1)
user.to_s  # returns <User:0x00000103ada530>
          

My question is, What is <User:0x00000103ada530> ? Is it like an ID of User? Is I enter <User:0x00000103ada530> will I get back User.find(1)

Thanks

like image 584
laman Avatar asked Jan 12 '23 01:01

laman


2 Answers

I could be wrong, but

0x00000103ada530

is address in memory
where you call User.new which is allocates memory space and the space has address: 0x00000103ada530

For example 2 instances of one class are not stores in the same place

class Test
end

t1 = Test.allocate # the same as Test.new, but just allocates a memory space for t1
t2 = Test.allocate
p t1 === t2  # false
p t1.inspect # "#<Test:0x007f17555ff398>"
p t2.inspect # "#<Test:0x007f17555ff370>"

If you need #to_s method for User you can set method

class User < ActiveRecord::Base
  . . .
  def to_s
   "#{first_name} #{last_name}"
  end
  . . .
end

User.first.to_s # => John Doe
like image 135
itsnikolay Avatar answered Jan 18 '23 05:01

itsnikolay


The #to_s method encodes the object's id as follows:

   (obj.object_id * 2).to_s(16)

If you want to get from the result of #to_s back to the object, you could use ObjectSpace if you are on MRI:

o = Object.new
o2 = ObjectSpace._id2ref(o.to_s.split(":").last.hex / 2)

o and o2 will now be references to the same object.

like image 30
Douglas A. Seifert Avatar answered Jan 18 '23 06:01

Douglas A. Seifert