Alexander Popov
Alexander Popov

Reputation: 24965

What does Ruby's using method do?

Metaprogramming Ruby chapter 3 has a task to write a Ruby equivalent of C#'s using statement. I started:

class Resource
  def dispose
    @disposed = true
  end
  def disposed?
    @disposed
  end
end
def using(r)
  puts "Not implemented."
end

r = Resource.new
using(r)

I have not implemented using yet. Nevertheless, when I run this code, I get

in `using': wrong argument type Resource (expected Module) (TypeError)

Furthermore, if I write something like using(Kernel), using(Enumerable), etc., the program finishes without error. As far as I know, there is no using method or keyword in Ruby, but I also get the same behaviour in pry and irb. What is happening?

Upvotes: 3

Views: 152

Answers (2)

phoet
phoet

Reputation: 18845

If you want to do that in Ruby 2.1 you will need to patch the main object, as it already has the method like it's mentioned in the comments:

self.instance_eval do
  def using(r)
    puts "Not implemented."
  end
end

Upvotes: 1

dee-see
dee-see

Reputation: 24078

There should not be a using method as pointed out in the comments. Try running method(:using).owner to see if you get any more information. The expected result on irb is

"NameError: undefined method `using' for class `Object'"

but you should get the source of your using.

Upvotes: 1

Related Questions