Mark
Mark

Reputation: 163

What does a Ruby instance variable with a preceding colon mean (:@name)?

I'm working through Ruby Koans and got to question #193:

  class Dog2
    def set_name(a_name)
      @name = a_name
    end
  end

  def test_instance_variables_can_be_set_by_assigning_to_them
    fido = Dog2.new
    assert_equal [], fido.instance_variables

    fido.set_name("Fido")
    assert_equal [___], fido.instance_variables
  end

The answer is "assert_equal :@name, fido.instance_variables". I know the colon (:) designates a symbol and the atsign (@) designates an instance variable. However, I haven't found documentation about what a combined colon and atsign means.

What does it mean and how is it used? Thanks!

Upvotes: 1

Views: 413

Answers (1)

Ajedi32
Ajedi32

Reputation: 48368

It's just a regular symbol:

:@name
#=> :@name
:@name.class
#=> Symbol

According to the documentation for Object#instance_variables:

instance_variables → array

Returns an array of instance variable names for the receiver. Note that simply defining an accessor does not create the corresponding instance variable.

class Fred
  attr_accessor :a1
  def initialize
    @iv = 3
  end
end
Fred.new.instance_variables   #=> [:@iv]

So here Ruby Koans is saying that fido.instance_variables should be equal to an array containing the symbol :@name.

assert_equal [:@name], fido.instance_variables

Upvotes: 6

Related Questions