1

As you can see in these questions, I have to return a Ruby class method twice.

# # 5a. Create a class called Animal that initializes with a color. Create a method in the class called legs that returns 4.

class Animal 
  def initialize(color) 
  @color = color
  end 

  def legs 
    legs = 4
     p "My animal has #{legs} legs"
  end
end 


# 5b. Create a new instance of an Animal with a brown color. Return how the number of legs for the animal object.
p Animal.new('brown') 

I don't receive any error messages. The methods just don't return, I've tried "puts" as well, but I must be missing something else.

Thanks!

Sebastian
  • 55
  • 1
  • 6

2 Answers2

3

The simplest change to get what you are looking for is this:

class Animal 
  def initialize(color) 
    @color = color
  end 

  def legs 
    4
  end
end 

example usage

Animal.new("brown").legs 

# => 4
  1. This meets the requirement to allow the object to be initialized with a color
  2. And provides a method that returns the number 4

As Josh said in his answer, you actually have to call the method on the object to see the result of the method.

The way ruby works is the the value returned by a method is the value returned by the last expression executed before the method returns, so if you swapped the order of the statements in your posted legs method your method would meet your requirement, however would have the side-effect of printing "My animal has 4 legs".

BTW p is not an alias for puts, see here and here for more info on puts

nPn
  • 16,254
  • 9
  • 35
  • 58
1

If you're expecting legs to be returned you need to call it.

animal = Animal.new('brown')
puts animal.legs

But...

You're returning nil in your method because you're calling puts in legs (aliased p) which returns nil.

(puts "hi").class # NilClass

puts nil #

So remove the p "My animal has #{legs} legs" and instead replace it with "My animal has #{legs} legs" and then call it:

puts animal.legs

Josh Brody
  • 5,153
  • 1
  • 14
  • 25
  • 2
    2 minor comments: 1) p is not an alias for puts (see the links I posted in my answer) and 2) The requirement seems to be to return the number of legs, not a string with some info around the number of legs. – nPn Aug 31 '19 at 01:43
  • Thank you Josh! you and @nPn have explained this neatly and concisely! – Sebastian Aug 31 '19 at 22:39