Sebastian
Sebastian

Reputation: 55

Returning methods in Ruby

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!

Upvotes: 1

Views: 59

Answers (2)

nPn
nPn

Reputation: 16728

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

Upvotes: 3

Josh Brody
Josh Brody

Reputation: 5363

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

Upvotes: 1

Related Questions