'Why do I not need the extra lines of code? Ruby Codeacademy

I'm working on Learn Ruby in Codeacademy (OBJECT-ORIENTED PROGRAMMING II: Private! Keep out!).

Why don't I need to include '(id_name)' after the 'def id' method for the final section?

My attempt is demonstrated in the top code, but the Codeacademy solution tells me that my approach is wrong and the correct approach is much more concise - as shown at the bottom.

class Dog
  def initialize(name, breed)
    @name = name
    @breed = breed
  end

  public
  def bark
  puts "Woof!"
  end

  private
  def id (id_number)
  @id_number = id_number
  id_number = 12345
  end
end

Correct version

  private
  def id
  @id_number = 12345
  end
end


Solution 1:[1]

Why don't I need to include '(id_name)' after the 'def id' method for the final section?

I assume you mean (id_number) – that's what we call a method argument.

Based on the proposed solution:

def id
  @id_number = 12345
end

... it seems like this method is supposed to set the instance variable @id_number to a fixed value of 12345. In order to do so, you don't need any value from the outside.

However, you could pass the value into the method via:

def id(value)
  @id_number = value
end

But now, you have to pass a value when calling the method. Omitting it would result in an ArgumentError, which might break existing code.

A third option is to have an argument with a default value:

def id(value = 12345)
  @id_number = value
end

This makes the argument optional. If you pass a value, it will be assigned to @id_number. Otherwise (i.e. if you call the method without passing an argument) the value 12345 will be used.

Note that value is just a name, you could use any other name as well, e.g. id_number. Just keep in mind that id_number and @id_number are different variables. The former being a local variable and the latter being an instance variable.

Regarding your code:

def id(id_number)
  @id_number = id_number
  id_number = 12345
end

This assigns the passed argument value to @id_number. It then assigns 12345 to the local variable id_number, thus overwriting its previous value. However, since the variable is never used after the assignment, that line is superfluous. Your code is equivalent to:

def id(id_number)
  @id_number = id_number
end

This is the same as my 2nd example above. (just with another argument name)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1