John123 John123 - 2 months ago 6
Ruby Question

Changing the name on this Ruby class causes an error

I have the following code and it runs as it should:

class Array
def my_name
first_name = "Bob"
last_name = "Smith"
yield(first_name, last_name)
end
end

['a', 'b', 'c', 'd'].my_name {|i, x| puts "#{i} #{x}"}


But the moment I change the class name from "Array" to something else, say "Array1", I get the following error:

`<main>': undefined method `my_name' for ["a", "b", "c", "d"]:Array (NoMethodError)


I'm not sure what that error means but its breaking my code. This is the broken code:

class Array1
def my_name
first_name = "Bob"
last_name = "Smith"
yield(first_name, last_name)
end
end

['a', 'b', 'c', 'd'].my_name {|i, x| puts "#{i} #{x}"}


For the life of me I can't figure out what's wrong. I'm really just trying to figure out how to use the yield function on methods within a class. I'm really having trouble with that and if someone could help me it would be greatly appreciated. Thanks!

Answer

['a', 'b', 'c', 'd'] is an instance of class Array (not of Array1 class). To be able to call methods defined in class Array1 you should first create an instance of that class.

Array1.new.my_name {|i, x| puts "#{i} #{x}"}
# Bob Smith
#=> nil