I like how you instantiate a URI object using the name of the URI class:
uri = URI('https://www.example.com')
Very neat and simple. How do you do that?
For example, suppose I have a module:
module MyModule
def self.mymethod()
end
end
MyModule.mymethod is the only method in the module. It's annoying that every time I want that method I have to type:
MyModule.mymethod()
It works, but it seems redundant... it's the only method in the module. Is there a way to only have to call MyModule?
MyModule.mymethod()
If you look at the source closely you’ll find this:
module Kernel
#
# Returns +uri+ converted to an URI object.
#
def URI(uri)
# ...
end
module_function :URI
end
Maybe disappointing to you, but if you do URI('https://www.example.com')
you just call a method inherited from kernel.
In your example, URI
is just a method named URI
. As idmean shows in their answer, it's defined as a module_function
in Kernel, which makes it available everywhere, and there are probably good reasons for doing it that way, but just defining it as a normal method in the main scope will accomplish largely the same thing:
def MyModule
puts "Called MyModule"
end
MyModule()
# => Called MyModule
See it in action on repl.it: https://repl.it/@jrunning/SnowHauntingLevels
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With