0

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!

John123
  • 301
  • 3
  • 19
  • BTW - `yield` is not a function, but a keyword (i.e. same status as `def` or `end`, not the same status as e.g. `puts`). – Amadan Oct 03 '16 at 07:06

2 Answers2

3

For unknown reason you are trying to call the newly introduced method on the Array instance. Just call it where it belongs:

Array1.new.my_name { |i, x| puts "#{i} #{x}" }
Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160
2

['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
Andrey Deineko
  • 51,333
  • 10
  • 112
  • 145
  • 1
    Subclassing arrays is a bad, bad idea. Doubly so if it's done just to add a method. – Sergio Tulentsev Oct 03 '16 at 06:46
  • But I guess here's where I'm confused. I put the two classes I specified earlier in separate files. Shouldn't they run individually? Why is ['a', 'b', 'c', 'd'] and instance of Array if Array doesn't even exist in my .rb file? – John123 Oct 03 '16 at 06:50
  • 2
    @John123 Array is a core class. You always have access to it and its methods. – Andrey Deineko Oct 03 '16 at 06:51
  • 1
    Why for God’s sake anybody would subclass `Array` here? What specific `Array` behaviour is required to call a method `my_name`? – Aleksei Matiushkin Oct 03 '16 at 06:53
  • 2
    @SergioTulentsev I never said it was good idea to subclass an Array. OP asked what is the problem with renaming the core class - I answered. He asked how to make it work - I showed. You're right that it is not needed to subclass an Array. – Andrey Deineko Oct 03 '16 at 06:54