JohnnyGat
JohnnyGat

Reputation: 335

how to get name of the instance? ruby

I know that self.class.name returns name of the class but how about instance?

For example this code

module Selling
  def sell
    puts "#{self.class.name} has been sold"
  end
end

class Shop
  include Selling
  def initialize(id)
    @id=id
  end
end

book=Shop.new(1132)
book.sell

prints Shop and what I need is a book

Upvotes: 1

Views: 63

Answers (2)

Stefan
Stefan

Reputation: 114158

Jörg W Mittag already explained that you can't inspect variable names.

Here's an attempt to solve your problem by using a separate Book instance with a name attribute:

module Selling
  def sell(item)
    puts "#{item.name} has been sold"
  end
end

class Shop
  include Selling
end

class Book
  attr_accessor :name
  def initialize(name)
    @name = name
  end
end

bookstore = Shop.new

book1 = Book.new('Moby-Dick')
book2 = Book.new('Of Mice and Men')

bookstore.sell(book1)
bookstore.sell(book2)

Output:

Moby-Dick has been sold
Of Mice and Men has been sold

Upvotes: 0

Jörg W Mittag
Jörg W Mittag

Reputation: 369438

Objects don't have names. They may or may not be referenced by one or more variables, but there is no way to know what variables reference an object and what the names of those variables are.

Modules are a special case, their name method indeed returns the name of the first constant that they have been assigned to, but that is interpreter magic.

Upvotes: 2

Related Questions