user3604867
user3604867

Reputation: 143

Basic Ruby class - correct code so it returns expected value

Extremely basic, yet I can't figure it out! Noob issues - I have tried several different answers for this, and I am still getting argument errors. Can someone please help enlighten me on the correct answer?

Correct this code, so that the greet function returns the expected value.

class Person
  def initialize(name)
    @name = name
  end

  def greet(other_name)
    "Hi #{other_name}, my name is #{name}"
  end
end

Upvotes: 0

Views: 2449

Answers (2)

Uri Agassi
Uri Agassi

Reputation: 37409

name is not available in greet. You can either use @name, or add an accessor:

class Person
  def initialize(name)
    @name = name
  end

  def greet(other_name)
    "Hi #{other_name}, my name is #{@name}"
  end
end

or

class Person
  attr_accessor :name

  def initialize(name)
    @name = name
  end

  def greet(other_name)
    "Hi #{other_name}, my name is #{name}"
  end
end

Upvotes: 4

Martin Konecny
Martin Konecny

Reputation: 59611

class Person
  def initialize(name)
    @name = name
  end

  def greet(other_name)
    "Hi #{other_name}, my name is #{@name}"
  end
end

You need to access your instance variables by prefixing the variable name with @. Just the same way as when you assigned it.

Upvotes: 6

Related Questions