makersacademy / problem-solving

For problem-solving during the PreCourse
6 stars 2 forks source link

private method 'fizzbuzz' called #88

Closed SaphMB closed 7 years ago

SaphMB commented 7 years ago

Hi, when using the alternative version of the rspec test:

it 'returns "fizz" for the number 3' do expect(3.fizzbuzz).to eq 'fizz' end

I'm getting the below error:

 Failure/Error: expect(3.fizzbuzz).to eq 'fizz'

 NoMethodError:
   private method `fizzbuzz' called for 3:Fixnum
 # ./spec/fizzbuzz_spec.rb:5:in `block (2 levels) in <top (required)>'

Does anyone have any insight?

paulmillen commented 7 years ago

As I understand it, when you call an argument using the argument.method structure, this will only work if the object (that is the argument) is allowed to use that method. ie is this private method something which is in the scope of its class?

The error message you are getting is Ruby saying "fizbuzz isn't a method for 3 (which is an object of the Fixnum class).

To call the method like this you have to give the method to the class in question, and structure the method to use the "self" keyword, so:

class Fixnum
  def fizzbuzz
   puts "fizz" if self % 3 == 0
  end
end
SaphMB commented 7 years ago

Thanks a lot Paul! That makes perfect sense!