John123 John123 - 2 months ago 6
Ruby Question

Passing in an array for a Ruby Class

I have the following code:

class MyGreeting
def initialize(name)
# Instance variables
@name = name
end

def say_hello
name.each do |x|
puts "Hello #{x}"
end
def say_bye
name.each do |x|
puts "Bye #{x}"
end
end

obj = MyGreeting.new([“johnny”, “kyle”, “sid”])
obj.say_hello


I am trying to make a class called MyGreeter that receives an array of values that are then used in the class. In the code above, I kinda show what I'm going for. I am trying to have the method say_hello output "hello johnny" "hello kyle" hello sid" when used. Right now I am getting an error that I cannot resolve. Any assistance is appreciated.

This is the error i'm receiving
syntax error, unexpected end-of-input, expecting keyword_end

nc. nc.
Answer

Like Cary Swoveland says above, you need ends to go with your dos. You also need to change name to @name in the say_ methods.

Here's a working version:

class MyGreeting  
  def initialize(name)  
    # Instance variables  
    @name = name
  end  

  def say_hello  
    @name.each do |x|
      puts "Hello #{x}" 
    end
  end 

  def say_bye  
    @name.each do |x|
      puts "Bye #{x}" 
    end
  end  
end

obj = MyGreeting.new(["johnny", "kyle", "sid"])
obj.say_hello
Comments