Instantiating defaults and variables

132 Views Asked by At

So I have a class Ball. in Ball we have a method type. What I want to do is return a string of the type of ball. The tricky part: if ball has no argument, I want to return string "standard". This handles the no argument case just fine. However, the "football" case keeps throwing and ArgumentError 1 for 0 error. What I'm trying to do is set a default of "standard" for if there is no argument passed to type and to print a given argument (given it's a string). How do I fix the ArgumentError? I've tried using splat and just taking 0 arguments already. Neither worked

class Ball
  def type(ball="standard")
      ball
    end
end

Test.assert_equals Ball.new("football").ball_type, "football"
Test.assert_equals Ball.new.ball_type, "standard"
1

There are 1 best solutions below

2
On BEST ANSWER

Since you're calling new on Ball, you should rename the type method to initialize. This method will automatically be called when a new instance of Ball is constructed.

class Ball
  def initialize(ball = "standard")
    @ball = ball
  end
end

@ball = ball means that the ball argument is saved to the @ball instance variable.

It also looks like you want a method for accessing the ball type when you call Ball.new.ball_type:

class Ball
  def initialize ... end

  def ball_type
    @ball
  end
end

This method simply returns the value of the @ball instance variable, which was set in the initialize method.

After these modifications:

Ball.new("football").ball_type # => "football"
Ball.new.ball_type # => "standard"