0

Hi I'm working on Ruby Koans. I was wondering why the ArgumentErrorwould be raised if the Dog6.new is returned in the code down below?

class Dog6
  attr_reader :name 
  def initialize(initial_name)
    @name = initial_name 
  end
end

def test_initialize_provides_initial_values_for_instance_variables
  fido = Dog6.new("Fido")
  assert_equal "Fido", fido.name
end

def test_args_to_new_must_match_initialize
  assert_raise(ArgumentError) do
    Dog6.new
  end
end

Is it because Dog6.newdoesn't have any arguments? Thank you!!

3 Answers 3

2

Yes, your assumption is correct.

Dog6.new implicitly calls Dog6#initialize to initialize the newly created instance (one might think about MyClass#initialize as about the constructor for this class,) which apparently has one required argument. Since no argument was given to the call to Dog6.new, the ArgumentError is being raised.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the explanation! Now I understand :)
1

Just adding that if you want to have a constructor with no arguments (after all - some dogs don't have a name....) you could have a default value for the name parameter.

def initialize(name = nil)
  @name = name
end

3 Comments

Adding default value will break the test. It is by no mean an applicable solution.
Indeed! You'll have to change the tests first obviously. :-)
I would rather remove that test though. Testing for all possible ArgumentError's does not seem constructive to me.
0

In the initializer for the Dog6 class, initial_name is defined as a parameter required for object construction. If this class were to be instantiated without this argument, an ArgumentError would be raised because the class definition has a method signature such that Dog6.new is invalid, like you guessed. In this case the error you would see would be:

ArgumentError: wrong number of arguments (0 for 1)

Read more about the ArgumentError exception here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.