0

I was wondering if there is any way to call the variable name that an instance of a class is set to from within the class itself in Ruby. I want to do the following.

class Playlist
  def display
    puts "the name of this playlist is ___"
  end
end

alternative = Playlist.new 
alternative.display
# => "the name of this playlist is alternative"

I need help filling in the blank so that calling display will return what I want.

3
  • Not really, at least no real way that makes sense. That said, I can't think of too many reasons why you'd really want to. Consider a playlist named "new songs", and you go all explodey. A Playlist should have a name, not be one. If for some reason you're dead set against implementing something like how real playlists work, you could keep the playlist in a map which can have arbitrary string keys. Oct 3, 2014 at 19:00
  • You wrote "the variable name", but what makes it "the" and not "a"? Ruby doesn't disallow more than one variables to point to a single object. And not all objects are assigned to a variable. Your question is unclear.
    – sawa
    Oct 3, 2014 at 19:15
  • Grabbing the variable name of the instantiated object is virtually unheard of. Most would design the Playlist class with an initialize method and assign the name when the playlist is created like Playlist.new("NameofPlaylist"). Even so I'm intrigued by the question and I'm digging deep into the Ruby core to find if this is possible. Just know that the way you're asking to have it done isn't the way it's designed to be done.
    – 6ft Dan
    Oct 3, 2014 at 19:21

2 Answers 2

2

Unconventional method (solves the question you posed)

Okay. For the sake of posterity I'll put the code here on how to accomplish what you asked. Remember this is NOT the way the language was meant to be used. But if you get into meta-programming this will be very useful knowledge.

class Playlist
  
  def display
    puts "Your playlist name is #{name}"
  end

  private
  def name
    scope = ObjectSpace.each_object(Binding).to_a[-1]
    scope.
      local_variables.
      select {|i| eval(i.to_s, scope) == self}.
      map(&:to_s).delete_if {|i| i== "_"}.first
  end
  
end

alternative = Playlist.new
# => #<Playlist:0x00000002caad08> 
alternative.display
# Your playlist name is alternative

Details (how it works)

Alright let me explain the parts. ObjectSpace is where all objects get stored. You can see how many Objects exist by calling ObjectSpace.count_objects. The most useful feature, in my opinion, is the each_object method. With this method you can iterate over however many of any particular object which have been created. So for playlist you can call ObjectSpace.each_object(Playlist) and you get an Enumerable object. We can simply turn that into a list by appending .to_a on the end. But at this point you're getting the instances of Playlist in an Array like this: [#<Playlist:0x0000000926e540>, #<Playlist:0x000000092f4410>, #<Playlist:0x000000092f7d90>]. This is functional if you wanted to access them individually and perform some action. But this is not what you're trying to do since we don't have the instantiated variable name these instances are assigned to.

What we really want to call is the local_variables method and we want to call that in the main scope (not from within your classes scope). If you call local_variables from within your display method you get back an empty Array []. But if you call it in the main console after you've created an instance you would get back something like this [:alternative, :_]. Now we're talking! Now there's the issue of getting the scope from outside the class to be used within it. This was tricky to track down. Normally you could just pass in binding as a parameter, or even use TOPLEVEL_BINDING. But something I noticed showed me that these each create an instance of Binding that won't get updated any more. That means once you call TOPLEVEL_BINDING anything else you define, like another playlist, won't be updated and in your list of TOPLEVEL_BINDING.local_variables. This was a sad thing for me to find. But I discovered a way to solve this.

By calling ObjectSpace.each_object(Binding).to_a we now have a list of every binding instance. So we just need to know how to get the latest one that's up to date. After experimenting I found the last one will always be up to date. So we index by [-1]. Now we can call .local_variables on it and we will always get the latest collection of instance variables within the global scope. This is great! Now we just need to match the instance variable to the current Playlist that we're in. So we select from the global local_variables any that match the current instance. We need to call eval to get the instance, and with eval we need to tell it what scope to run in so we use select {|i| eval(i.to_s, scope) == self}. From there we take the symbols and map them to strings with .map(&:to_s) and lastly we have an extra item in our list we don't need. The underscore symbol is kind of a Ruby trick to get the last thing that was processed. So we'll need to remove it since it evaluated to the same id as our current variable instance did. So we do .delete_if {|i| i== "_"}. And lastly it's a list of one item, the thing we want, so we pick it out with .first

NOTE: This scope selecting method doesn't work in Rails. There are many bindings instantiated. The last one and the largest one with local_variables aren't the up to date ones.

This went through many unconventional means to accomplish the task you asked about. Now it may be you didn't know the standard way that something like naming a playlist class is done, and that's okay. No one knew at first, it is a learned trait.

Convential way to name a playlist

This is the preferred method for naming a playlist class.

class Playlist

  def initialize(name)
    @name = name
  end
  
  def display
    puts "Your playlist name is #{@name}"
  end

end

list = Playlist.new("Alternative")
list.display
# => "Your playlist name is Alternative"

This is rather straight forward. It's best to work with the way a language was designed to be used.

If I were you I would make list an Array of Playlist items and use it like this.

list = []
list << Playlist.new("Alternative")
list << Playlist.new("Rock")
list
# => [#<Playlist:0x000000028a4f60 @name="Alternative">, #<Playlist:0x000000028e4868 @name="Rock">]
list[0].display
# Your playlist name is Alternative
list[1].display
# Your playlist name is Rock

And now you have a list of playlists! Sweet!

When you get into meta-programming you may use a lot of features from the unconventional method here. meta-programming is where code writes code. It's fun!

5
  • Good solution (but not a good answer because it is not concise). But eval(i.to_s, scope).__id__ == self.__id__ can be simplified to eval(i.to_s, scope).equal?(self).
    – sawa
    Oct 4, 2014 at 6:29
  • Running the code works for me. Is there a specific version of Ruby that it wouldn't?
    – 6ft Dan
    Oct 4, 2014 at 6:33
  • No. If you have a = "foo"; b = "foo", what do you get?
    – sawa
    Oct 4, 2014 at 6:34
  • Why "foo", from :b. But == returns a true/false. Not one or the other value.
    – 6ft Dan
    Oct 4, 2014 at 6:37
  • 1
    @6ftDan Solid answer. 2014 me just couldn't appreciate it. Weirdly enough, I recently asked almost the exact same question without even remembering this! Only difference is I'm trying to do it on constant declaration instead of variable declaration. You can check out the question here. If you have any idea how to accomplish this I'd love to hear it. Promise I won't make you wait 4 years for the check mark this time.
    – Josh Hadik
    Jun 7, 2018 at 3:17
2

Here's why this isn't possible and doesn't make sense.

Imagine I added to your code:

n2_playlist = alternative
n2_playlist.display

What would n2_playlist display? n2_playlist? alternative? I have two references pointing to the same object. It's like a remote having the same programming instructions.

To make things more interesting, let's suppose:

[n2_playlist, alternative].each do |some_arg|
  some_arg.display
end

What should it display? some_arg? n2_playlist? alternative? Source

Or this:

Playlist.new.display #=> What should it print ? We have no variable pointing to it

With Playlist.new, you're creating a new object, and alternative and n2_playlist are just references to that object. As far as I'm aware, Ruby objects don't know (and don't care) about the references pointing to them. In Ruby, you can only manipulate objects. Variables are not objects. Source

It would be best to put the genre in the initialize method. That way you'll have an actual String object you can manipulate.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.