Skip to content

Instantly share code, notes, and snippets.

@armw4
Last active December 31, 2015 11:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save armw4/7979482 to your computer and use it in GitHub Desktop.
Save armw4/7979482 to your computer and use it in GitHub Desktop.
Setting instance variables in ruby is all about the current value of self. Just because you use @foo = bar...doesn't mean you'll get a new copy of foo for every instance of your class.

###by Antwan Wimberly###

class HiO
  def print_i
    # note...this won't print 12...even though we set
    # this variable in the `toast` method
    puts "my var is #{@var}"

    # and neither will this...failure!!!
    #puts @@var

    # but this however...will!!!
    puts self.class.instance_variable_get "@var"

    # I wonder if we can overrite `var`?
    @@var = 19

    # do you think it will print 19...or 12?
    # nope...prints 12 as we're now
    # pointing to the original @var that `toast` set
    puts self.class.instance_variable_get "@var"

    create_new_instance_and_then_print_var
    
    # this is weird...we've got an instance of a `Class` which can have instances of 
    # itself well...turns out that every time we say `self.class`, it returns the
    # same thing! ruby will make only one instance of that guy
    
    # this will print true and they both have 12 for var as they're the same instance
    # of the same `Class`
    puts "classes are equal #{self.class.object_id === self.class.object_id}"
  end

  def create_new_instance_and_then_print_var
    # do you think it will say 19?
    #
    # yes it does...twice...all instances will from this point forward because
    # we put the value on the `Class`.
    #
    # you must be wondering though...
    #
    HiO.new.print_var
    HiO.new.print_var
    
     # if we've got two variables named var on the `Class`, then why don't
    # they collide?
    #
    # *shrugs*
    
    # ok...I lied...they're not pointing to the same thing
    puts HiO.class_variables # this would be the `@var` that `toast` set
    puts HiO.instance_variables # this....would be the `@@var` guy...make sense???
    
    # I'll tell you that the @@var guys can be very dangerous...beware..any derived
    # classes will also see the same value and can manipulate that guy thus changing
    # if for any other derived classes (in addition to the original base clase)
  end

  def print_var
    puts @@var
  end

  def self.toast
    @var = 12
    puts "Current value for @var is #{@var}"
  end
end

HiO.toast
HiO.new.print_i
@armw4
Copy link
Author

armw4 commented Dec 15, 2013

You'll really get a kick out of what this guy has to say. This article may be old but it's far better than my oh so convoluted gist could ever be. It's all just practice right?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment