class Human # Problem received from Raul Romero
attr_reader :name
def initialize(name)
end
end
gilles = Human.new("gilles")
anna = Human.new("gilles")
puts anna.equal?(gilles) #should output true #
puts anna gilles # should output annagilles
How do I make the last line of code output annagilles?
CodePudding user response:
Alright, there are a couple of things you might need to complete your Human class:
class Human # Problem received from Raul Romero
attr_reader :name
def initialize(name)
@name = name
end
end
you need to set the instance variable @name in order to read it.
next your puts anna.equal?(gilles)
check wont work because .equal? checks if you are dealing with the same object. likewise "a".equal("a") #=> false
, so in your case only anna.equal?(anna)
will return true.
then puts anna gilles
shouldnt work because you are trying to add two instances together (not their names). so maybe this would work:
gilles = Human.new("gilles")
anna = Human.new("anna") # note that you have 'gilles' here in your example
puts anna.name gilles.name #=> 'annagilles'
so in order to get the value you passed to the initialize (which is then set to @name) you need to call that value with .name, ie some_human.name
CodePudding user response:
if you need to get result using then below is the solution
class Human
attr_reader :name
def initialize(name)
@name = name
end
def (other)
name other.name
end
end
gilles = Human.new("gilles")
anna = Human.new("anna")
puts anna.equal?(gilles)
puts anna gilles
output
false
annagilles
but i preferred blow solution
class Human
attr_reader :name
def initialize(name)
@name = name
end
def (other)
Human.new(name other.name)
end
def to_s
name
end
end
gilles = Human.new("gilles")
anna = Human.new("anna")
puts anna.equal?(gilles)
rerult = anna gilles
puts rerult.to_s
output
false
annagilles