Ruby: Difference between Topic.methods and Topic#methods [duplicate] - ruby

In Ruby what is the difference between those two (in code):
Class.method
Class#method

It's a naming convention.
use pound #method for instance methods
use dot .method for class methods
See: How to name RSpec describe blocks for methods

The hash format (Class#method) is not valid ruby, but is used in documentation to describe an instance method.
Class methods are typically documented using a double-colon (Class::method).
You will see examples of both in the ruby docs (e.g. http://www.ruby-doc.org/core-1.9.3/String.html)
The dot format is used in code when actually calling a class method (Class.method), though I have seen some people (unfortunately) use it interchangeably with either the double-colon or hash in documentation.

Class#method is not valid code. It is only used in documentation. method should be an instance method.
Class.method or object.method is the actual method belonging to the object. Class is an object too. It is valid code.

Related

In ruby, what is the vocab word for `attr_accessor`?

In Ruby, you can add attr_reader, attr_writer or attr_accessor to a class to generate accessors and mutators for an instance variable. In Rails, model validations and controller filters are added using a similar syntax.
I know that under the hood this is a method that runs when the class is defined, which generates some code and attaches it to the class.
What I'm looking for is a vocab word to describe this pattern. My searching has come up with "[code ]generator" and "helper", and I think I like "generator" the best, but I wonder if there is an official word for it.
Sources:
https://mikeyhogarth.wordpress.com/2011/12/01/creating-your-own-attr_accessor-in-ruby/
http://codeatmorning.com/ruby-attr_accessor-what-is-that/
When code generates or expands into other code, it can be called a macro.
https://en.wikipedia.org/wiki/Macro_(computer_science)
The book "The Ruby Programming Language" (Flanagan, Matsumoto) refers to it as metaprogramming (pg. 219)

Idiomatic use of double-colon (double-column, or ::) syntax for Ruby methods

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.

Difference between . and #

In Ruby what is the difference between those two (in code):
Class.method
Class#method
It's a naming convention.
use pound #method for instance methods
use dot .method for class methods
See: How to name RSpec describe blocks for methods
The hash format (Class#method) is not valid ruby, but is used in documentation to describe an instance method.
Class methods are typically documented using a double-colon (Class::method).
You will see examples of both in the ruby docs (e.g. http://www.ruby-doc.org/core-1.9.3/String.html)
The dot format is used in code when actually calling a class method (Class.method), though I have seen some people (unfortunately) use it interchangeably with either the double-colon or hash in documentation.
Class#method is not valid code. It is only used in documentation. method should be an instance method.
Class.method or object.method is the actual method belonging to the object. Class is an object too. It is valid code.

On which object/class does DelegateClass and similar methods live?

Sorry for the poor title, but I'm a bit lost.
I'm trying to figure out on which object/class live methods such as DelegateClass and what is the term for these types of methods. I'm reading Metaprogramming Ruby and, in the book, these methods are generically called Mimic Methods, but searching the internet for this gives all kinds of results, so I'm wondering if there's a better name for them.
I've checked the source code of DelegateClass and I assumed that it was added to Object, but it's not there. I can see the the classes Delegator and SimpleDelegator, which are in the same rb file, are added as constants (although I'm not sure how they are added).
Thanks!
Just found the answer. It's a private method in Object
ruby-1.9.2-p290 :033 > Object.private_instance_methods(false).grep /Dele/
=> [:DelegateClass]
edit
I found out that what I needed to understand is What is the current class? in a given context.
Look closer at the file.
def DelegateClass(superclass)
klass = Class.new(Delegator)
...
and use
method(:DelegateClass).owner
to find the class where it sits. As mentioned in the comments private instance methods on Module contain anything defined on Object.
So no, DelegateClass() is not a special method in any way except for being called in uppercase (which makes it look like a constant). It just returns an anonymous class created on-the-spot that can be inherited from.

method_missing in "Programming Ruby" over my head

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.

Resources