module Hints
module Designer
def self.message
"Hello, World!"
end
end
end
is there any way to use the following code to access the message method?
p Hints.Designer.message
Instead of
p Hints::Designer.message
The period . is only meant for accessing methods.
The double colon :: is used to indicate namespaces.
Both modules and classes can be nested in each other. This creates a namespace for the nested class. (Technically, Module is an instance of Class.) Thus, the following is correct no matter if Hints or Designer are a class or a module.
Hints::Designer.message
You can try yourself by opening irb on the command line. Hints.Designer.message says NoMethodError: undefined method 'Designer' for Hints:Module.
Update (as I am not allowed to comment...):
While many things in Ruby can be overwritten ("monkey patched"), basic operators cannot. :: is a basic language feature that is and should not be customizable (in order to prevent a big mess ;)).
You can use dot to access the message method, but you can't use it to access Designer module, because Designer it is not a method (but a constant). Dot is for invoking methods only.
Related
I have a Ruby module in a file called my_module.rb:
module My_module
def my_module_method
puts 'inside my method'
end
end
In a file my_class.rb in the same folder, I have a class contained within the module.
module My_module
class My_class
def my_object_method
My_module.my_module_method
end
end
end
My_module::My_class.new.my_object_method => 'undefined method 'my_module_method''
I was not expecting this error. I assumed that Ruby would run into the line 'My_module.my_module_method' and search for a module called 'My_module' and a method within it called 'my_module_method.' This is what Java does, for example. However, Ruby does not do this. In order to get my_object_method to work, I have to write in my_class.rb:
require 'my_module.rb'
Why doesn't Ruby search for My_module when I call my_object_method? It seems obvious what it should search for and therefore redundant to require the programmer to explicitly write 'yes, Ruby, please allow me to make calls to module-wide methods.' What am I missing?
Ruby doesn't automatically load files. If you need a code from some file, you have to load it (by calling require) explicitly.
Thus, when you run "ruby my_class.rb" it loads only this file and you have to define dependencies between files by yourself.
You seem to have a misunderstanding of how to define a class method. In order to make your method call work, you could define it as def self.my_method_name.
In both classes and modules, methods work the same when you define them as class methods using self. or alternatively the class << self syntax. However instance methods (methods without the self.) work differently in these 2 cases. In classes, as you seem to understand, they're accessible once you instantiate the class using .new. In modules, they're only accessible if you include or extend.
See also:
difference between class method , instance method , instance variable , class variable?
http://www.rortuts.com/ruby/ruby-include-vs-extend/
Oh any by the way. Ruby doesn't enforce any convention where you have 1 file per class (named identically). You need to manually require files wherever you need them. Although there are some frameworks such as Rails which auto-require files, and enforce naming conventions.
I am relatively new to Ruby and find it confusing that the following pairs of
examples work equally well:
File.included_modules
File::included_modules
File.stat('mbox') # Returns a '#<File::Stat..>' object
File::stat('mbox')
File.new("foo.txt", "w")
File::new("foo.txt", "w")
"asdf".size # An instance method
"asdf"::size
2 + 3
2::send(:+, 3) # An extreme example
File::new, in particular, is something I quite frequently encounter.
My question: Would it be non-idiomatic for me to avoid ever using the :: operator for qualifying the names of anything but classes, modules, and constants and, instead, consistently to use only dot syntax for all methods (class methods, module methods, and instance methods)?
To be clear: are there any situations in which I would want to refer to a method (whether in code or in documentation) using anything other than dot syntax?
Sources consulted:
2007: https://www.ruby-forum.com/topic/107527
2010: What is Ruby's double-colon `::`?
2010: What does ::MyClass Ruby scope operator do?
2010: https://www.ruby-forum.com/topic/315853
2011: Double colons before class names in Ruby?
2012: Ruby's double colon (::) operator usage differences
2014: Ruby class naming convention with double colon
http://www.tutorialspoint.com/ruby/ruby_operators.htm
Would it be non-idiomatic for me to avoid ever using the :: operator for qualifying the names of anything but classes, modules, and constants and, instead, consistently to use only dot syntax for all methods (class methods, module methods, and instance methods)?
No, it would in fact be idiomatic. Nobody ever uses :: to call methods, ever. Period.
The only time :: is used in conjunction with methods is when talking about methods. In that case, Foo#bar is used to talk about instance methods (i.e. a method bar that can be called on instances of Foo like foo.bar) and Foo::bar is used to talk about singleton methods (i.e. a method bar that can be called on Foo itself like Foo.bar). However, we only use :: for talking about methods, never for calling them.
Some notes:
Technically speaking, there are no class methods or module methods in Ruby. Every object can have methods defined only for itself (so-called singleton methods), and since classes and modules are also objects, they can also have singleton methods. So, we will sometimes talk about "class methods" or "module functions", but in reality, those are just singleton methods.
Well … actually, I lied. Sorry. Singleton methods don't exist either. They are really just normal instance methods of the singleton class of the object. But saying "instance method of the singleton class of the object" is a mouthful, so we just say "singleton method of the object", and likewise instead of "instance method of the class object's singleton class", we say just "class method". However, we only say this in the knowledge that those things actually don't really exist, and especially when talking to newbies, I prefer to use the long form instead of the short-form jargon.
:: is used to dereference constants inside modules. The fact that those constants often point to modules or classes is not significant. Here is an example of resolving a constant which doesn't point to a module or class inside a module that isn't referenced by constant:
module Foo; BAR = 42 end
foo = Foo
foo::BAR # => 42
# ^ ^------------ not a module
# |
# +---------------- not a constant
Would it be non-idiomatic for me to avoid ever using the :: operator for qualifying the names of anything but classes, modules, and constants and, instead, consistently to use only dot syntax for all methods (class methods, module methods, and instance methods)?
Regarding the :: for method calls, I don't think there is any situation where you cannot substitute it with ., or where :: is preferred.
[A]re there any situations in which I would want to refer to a method (whether in code or in documentation) using anything other than dot syntax?
When the receiver is self, it is generally preferred to omit the self and . unless the method is either of foo= form, or is either []= or class.
When there is need to distinguish from a local variable with the same name as the method, explicit receiver and . can also be used, but () can be used instead.
When you need to call a private method with a receiver other than self, you can use receiver.send(:method_name) or receiver.instance_eval{method_name}.
Are there any situations in which I would want to refer to a method (whether in code or in documentation) using anything other than dot syntax? [emphasis mine]
Some style guides (e.g. bbatsov's) recommend using :: syntax to call methods that are made to look like constructors.
# good
...
SomeModule::SomeClass()
"Methods that look like constructors" are generally methods with a capitalized first letter, such as Kernel#String, which looks like String(123) when you use it, or (as cited in the style guide linked above) Nokogiri::HTML(a_string), which is a singleton method on Nokogiri that has been made to look like a constructor for the class Nokogiri::HTML.
I have two versions of a simple program that accomplishes the same thing. I have some questions.
When should I use class functions over instance functions?
Are there any performance benefits of using class vs instance functions? Does one use more resource than the other given everything else constant.
Is defining a class function with self the same as defining it with the module's name (version 2 question)
Version 1: instance functions
I have a file called pastries.rb that contains:
module Pastries
def description
return "I am a pastry!"
end
end
Then in another file called main.rb, I have:
require 'pastries'
include Pastries
puts "With include: #{description}" # With include: I am a pastry!
Version 2: class functions
pastries.rb:
module Pastries
# Are the following equivalent?
# def self.info
# return "I am a pastry!"
# end
def Pastries.description
return "I am a pastry!"
end
end
main.rb:
require 'pastries'
puts "WITHOUT include: #{Pastries.description}" # WITHOUT include: I am a pastry!
Any feedback is appreciated. I am a newbie both on stackoverflow and in Ruby, so correction of posting style or other critiques are welcomed as well.
To start off, functions in Ruby are called Methods.
In version 1, you are using the Module with an instance method, which can be used in mixins (i.e., it is mixed in to a class) as above. Here, you are mixing it with the top-level object class in main.rb.
In version 2, you are using the Module(s) with class method(s), where the module acts as a namespace to avoid namespace collisions for these methods when it is used along with other modules and classes.
To your particular questions:
1. When should I use class functions over instance functions?
Class level methods within modules may be used when you want to provide direct access to a module's methods without the need of instantiating a class object (for ex. standalone libraries) or when you want to use the method in the scope of the object where it is mixed in.
Instance methods should be used when you want to call the module's method via a class object where it is mixed in (for ex. to provide additional functionality for a class and serve a mechanism for a class similar to multiple inheritance)
2. Are there any performance benefits of using class vs instance functions? Does one use more resource than the other given everything else constant.
As explained in 1 and 3, the benefits depend on the required usage. For memory consumption, AFAIK, no countable differences.
3. Is defining a class function with self the same as defining it with the module's name (version 2 question)
Not exactly. When you define a module method with module's name, it'll always be accessible in the scope of the module, while a module method defined with self will be accessed in the scope of the object from where it has been called. See the following answer for a detailed description: Trying to understand use of self.method_name vs. Classname.method_name in Ruby
Hope this helps, Cheers.
I was thinking wouldn't it be cool to have a print method defined in the Ruby Object class? Consider the following:
class Object
def print
puts self.to_s
end
end
23.times &:print
Is there any issue in having something like this? Seems like a good feature to have. It also appears easy to read.
There's already Object#inspect defined. Plus, there's already Kernel#print defined as private method in Object class and every class that inherits from it.
This method already exists in the Ruby standard library. However, it has a different name: display.
23.times &:display
# 012345678910111213141516171819202122
As you can see, it does not write a newline after the object's string representation; it is ill-suited for object inspection.
The main issue with adding methods to Object is that they become universal and may clash with similarly named methods in other libraries or in your project.
There are already multiple simple ways to output data or convert to string form in Ruby core, so the risk of a clash (on a very useful method name) likely outweighs any benefits from nicer syntax even in your own code.
If you have a smaller set of classes in your own project, where you feel this would be a useful feature to have, then this is an ideal use case for mix-ins.
Define a module:
module CanPrintSelf
def print
puts self.to_s
end
end
And include it in any class you want to have the feature:
class MyClass
include CanPrintSelf
end
my_object = MyClass.new
my_object.print
So you can have this feature if you like it, and you don't need to modify Object.
method_missing
*obj.method_missing( symbol h , args i ) → other_obj
Invoked by Ruby when obj is sent a
message it cannot handle. symbol is
the symbol for the method called, and
args are any arguments that were
passed to it. The example below
creates a class Roman, which responds
to methods with names consisting of
roman numerals, returning the
corresponding integer values. A more
typical use of method_missing is to
implement proxies, delegators, and
forwarders.
class Roman
def roman_to_int(str)
# ...
end
def method_missing(method_id)
str = method_id.id2name
roman_to_int(str)
end
end
r = Roman.new
r.iv ! 4
r.xxiii ! 23
r.mm ! 2000
I just heard about method-missing and went to find out more in Programming Ruby but the above explanation quoted from the book is over my head. Does anyone have an easier explanation? More specifically, is method-missing only used by the interpreter or is there ever a need to call it directly in a program (assuming I'm just writing web apps, as opposed to writing code for NASA)?
It's probably best to not think of ruby as having methods. When you call a ruby "method" you are actually sending a message to that instance (or class) and if you have defined a handler for the message, it is used to process and return a value.
So method_missing is a special definition that gets called whenever ruby cannot find an apropriate handler. You could also think of it like a * method.
Ruby doesn't have any type enforcement, and likewise doesn't do any checking as to what methods an object has when the script is first parsed, because this can be dynamically changed as the application runs.
What method_missing does, is let you intercept and handle calls to methods that don't exist for a given object. This provides the under-the-hood power behind pretty much every DSL (domain-specific language) written in Ruby.
In the case of the example, every one of 'r.iv', 'r.mm', and so on is actually a method call to the Roman object. Of course, it doesn't have an 'iv' or an 'mm' method, so instead control is passed to method_missing, which gets the name of the method that was called, as well as whatever arguments were passed.
method_missing then converts the method name from a symbol to a string, and parses it as a Roman number, returning the output as an integer.
It's basically a catch-all for messages that don't match up to any methods. It's used extensively in active record for dynamic finders. It's what lets you write something like this:
SomeModel.find_by_name_and_number(a_name, a_number)
The Model doesn't contain code for that find_by, so method_missing is called which looks at is says - I recognize that format, and carries it out. If it doesn't, then you get a method not found error.
In the Roman example you provide it illustrates how you can extend the functionality of a class without explicitly defining methods.
r.iv is not a method so method_missing catches it and calls roman_to_int on the method id "iv"
It's also useful when you want to handle unrecognized methods elsewhere, like proxies, delegators, and forwarders, as the documentation states.
You do not call "method_missing" (the interpreter calls it). Rather, you define it (override it) for a class which you want to make to be more flexible. As mentioned in other comments, the interpreter will call your version of method_missing when the class (or instance) does not ("explicitly"?) define the requested method. This gives you a chance to make something up, based on the ersatz method/message name.
Have you ever done any "reflection" programming in Java? Using this method would be as if the class to be accessed via reflection could look at the string (excuse me, "symbol") of the method name if a no-such-method exception was thrown, and then make something up as that method's implementation on the fly.
Dynamic programming is kind of a "one-up" on reflection.
Since you mention web apps I'll guess that you are familiar with Ruby on Rails. A good example of how method_missing can be used is the different find_by_<whatever> methods that's available. None of those methods actually exist! They are synthesized during run time. All of this magic happens because of how ruby intercepts invocations of non-existing methods.
You can read more about that and other uses of method_missing here.
ActiveRecord uses method_missing to define find_by methods. But since, method_missing is basically a last resort method, this can be a serious performance bottleneck. What I discovered is that ActiveRecord does some further awesome metaprogramming by defining the new finder method as a class method !! Thus, any further calls to the same finder method would not hit the method_missing because it is now a class method. For details about the actual code snippet from base.rb, click here.