Why is the new method not needed for creating Rational in ruby [duplicate] - ruby

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Ruby syntax question: Rational(a, b) and Rational.new!(a, b)
I'm in the process of reading the ruby pickaxe book, and I'm confused about the syntax of creating rational numbers.
Rational(3,4) * Rational(1,2)
produces
=> 3/8
Why is the new method not needed for Rational (I also noticed for example I can create a string without the new method)?

For one thing, Ruby has no new keyword. new is a class method that all classes have (they inherit it from Class) that creates an object of that class. When you see something like Rational(3,4), Rational is really just a private method of Object (defined in Kernel) that makes creating rational numbers easier. For more on those constructor-methods, see this answer of mine: https://stackoverflow.com/a/9677125/1008938

It's a method that happens to have the same name as the class. It's a common conversion idiom in Ruby.

Related

'to_a' is not a method in 'Range', yet, it works on 'Range'?

The following code is valid:
(1..5).to_a
(1..5) is a Range. The method to_a appears to convert a range to an array.
However, the documentation for Range does not document. Since this documentation is presumably auto-generated from the source with Yard, I doubt it could not be in the list of methods. Is there auto conversion going on?
How is the above legal Ruby?
The following code is valid ruby:
b = (1..5).to_a
(1..5) is a Range object, and b is an Array object. The official(?) documentation for the Class Range does not document the method to_a, which appears to convert a range to an array.
So, how is the above legal Ruby?
Ruby has something called "inheritance". Inheritance is a method for differential code-reuse that actually does not only exist in Ruby, but is in fact quite popular in many languages such as Java, C♯, C++, Python, PHP, Scala, Kotlin, Ceylon, and so on and so forth.
Inheritance allows you to define methods in one place, and then inherit them in another place, overriding and defining only the methods whose behavior differs. Hence, "differential code re-use".
In this particular case, the method you are looking at is Enumerable#to_a.
Note: Ruby actually has two forms of inheritance, mixin inheritance and class inheritance. Mixin inheritance is like class inheritance where the mixin doesn't know its superclass. (The definitive resource about mixin inheritance is Gilad Bracha's PhD Thesis The Programming Language Jigsaw –􏰀 Mixins,􏰁 Modularity, and Multiple Inheritance.)
The official(?) documentation
Actually, ruby-doc is a third-party site. There is no official documentation site. (However, the documentation on ruby-doc is generated from documentation comments in YARV, one of the major Ruby implementations, and one that Yukihiro Matsumoto actively contributes to.)
Since this documentation is presumably autogenerated from the source with Yard,
It is actually autogenerated from the YARV source with RDoc, not YARD.
I'm confused how it could not be in the list of methods,
Note that the explanation I gave is the correct one, but there could be many other explanations. The most simple one: the reason why the method is not in the documentation is that it is not documented. Another reason could be a bug in the documentation generator that prevents the documentation for that method being displayed, a typo in the source code that prevents the documentation generator from recognizing the documentation, and many, many others.
so is there auto conversion going on?
No. Ruby does not have automatic conversions in the language. There are some methods which for reasons of efficiency are implemented in a non-object-oriented manner, and require an object to be an instance of a specific class (as opposed to the object-oriented manner, which would only require the object to conform to a specific protocol). Because it is a severe restriction to require an object to be an instance of a specific class, those methods will usually offer an "escape hatch" to the programmer, by sending a specific message and allowing the object to respond with an object of the required class.
For example, all methods printing something to the console, require an instance of String, but they will try sending to_s first, before rejecting the argument.
These are sometimes called "implicit conversions", but they have nothing to do with implicit conversions as in Scala or implicit casts as in C♯. They are in fact not even part of the language, they are just a convention for library writers.

Are Symbols in Ruby Made with Constructors or Initializers?

In the answer to this SO question Jörg W Mittag says:
There is no such thing as a constructor in Ruby.
I didn't think much of that, until I read the Wikipedia article on constructors, which states:
Immutable objects must be initialized in a constructor.
Since symbols are immutable in Ruby, how are they made? Wikipedia would seem to think they must be made with a constructor, yet Jörg says there are no constructors in Ruby.
I'm fairly new to OOP concepts and programming in general, so it possible I am missing something fairly basic, but from my perspective it there is a contradiction between these sources.
When people say
There is no such thing as a constructor in Ruby.
they mean that there is no special method type corresponding to a constructor, the way there is in C++ and Java.
In Ruby, the initialize method is, by convention, used to initialize a new object. However, it is not a special method -- it's a method just like any other method in Ruby.
Symbols are 'initialized' in some dark inside part of the ruby runtime, that you don't need to worry about.
If you make your own immutable class in ruby, it would have to be initialized in it's "constructor", which in ruby means in it's #initialize method. The initialize method may or may not technically be a constructor, but it's the method that is called when the object is instantiated, which is the point the wikipedia article is making -- since an immutable object can't be changed once created, any state has to be set when it's created, not later.
Wikipedia article calls this 'a constructor', but different languages use different terminology or exact constructs, the wikipedia article wasn't written with ruby in mind. For ruby, "place you can set state on object instantiation" is typically initialize method. (I say 'typically', because you can do all kinds of crazy things in ruby if you try). The wikipedia article is still right that if an object is truly immutable, any setting of state happens to happen on object creation, not afterwords -- that's just the meaning of 'immutable', right?
That's for immutable classes implemented by ruby source code. But good luck finding an 'initialize' method for symbols. They don't work that way. They are just provided by ruby itself, by the runtime, and we don't need to worry about the details.

Defining custom operators in ruby [duplicate]

This question already has answers here:
Define custom Ruby operator
(3 answers)
Closed 9 years ago.
I would like to be able to define custom operators. Is that possible? For example, to make a***b mean something.
Is it also possible to monkey patch existing operators? To, for example, make a**b always return a float?
Yes, you can. For example:
class Fixnum
def **(x)
self.*(x)*1.0
end
end
5**4 #==> 20.0
Custom operators? Not unless you want to hack the C parser (or Java parser for JRuby or ...). OTOH, operators are mostly syntactic sugar for methods and you're allowed to defined all the methods you want.
Since many operators (but not all) are just methods in disguise, you can monkey patch the implementations of existing operators as much as you want to. You'd have to track down all the numeric classes that define their own ** implementation and patch all of them; note that you'd need to cover Rational, Complex, ... from the core as well as things like BigDecimal from the standard library. I'd strongly recommend against doing this, you'd just be setting yourself up for pain and suffering; for example, what would you do with BigDecimal#** when the result doesn't fit in a Float? What about Complex#**? If you need Floats for something, make it explicit with a to_f call.

What are the major differences between Ruby 1.8.6 and 1.9.1? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the difference between Ruby 1.8 and Ruby 1.9
I have found some differences in interpretation of global and local variables.
Can anyone point me to list of major differences?
These are probably the most important changes:
Ruby 1.9 changed from being
interpreted to being
bytecode-compiled (using the YARV
VM).
The String class has been redesigned
entirely to make it encoding-aware.
Regular expressions are now
implemented using the Oniguruma
engine, rather than the home-made one
used in ruby 1.8, enabling new
features like negative look-around.
The enumerator library from stdlib
has been added to core and most
Enumerable methods have been
changed to return an Enumerator
when invoked without a block.
Symbol#to_proc has been added.
There's a new syntax for lambdas,
-> which allows default arguments
and lambdas taking blocks.
There's a more complete list of changes here.
One major point might be that they use a different VM (at least, the 'standard' distributions do, obviously there are a number of options like MacRuby, IronRuby, etc). You might have a look here for details on all the changes.

Why are methods in Ruby documentation preceded by a hash sign?

When I see any Ruby method printed in text, it usually appears as:
Class#method
or
#method
Now, I would use:
Class.method
Why are all Ruby methods preceded by a pound sign? Is there any reason for it?
Note that the convention is:
Class#method
rather than
object#method
In code you would have object.method, if object was an instance of class. The # convention is not used in code.
From the RDoc documentation:
Use :: for describing class methods, # for describing instance methods, and use . for example code.
The # notation is used to refer to the canonical instance method, like String#upcase. The . notation is used to refer to the method of a particular instance, like mystring.upcase. The distinction is made to not imply that a class method 'upcase' exists.
I just realized that none of the other answers touch the most trivial aspect of the question: why the # sign?
I have two theories:
It might come from Smalltalk, where symbols are written #sym (instead of :sym) as they are in Ruby. So, if you want to refer to a Method object (as opposed to calling a method), then you would call something like Array >> #new. (The >> is itself a method that returns the method passed to it. So, in Ruby that would be Array.method :new.) In Smalltalk documentation, methods are generally referred to as Class>>method, but in Ruby Class:method would have made more sense, except that it is easily confused with Class::method. Therefore, Class#method was chosen.
My other theory is that it simply was chosen because # is the comment character in Ruby.
A definitive answer can only be given by whoever invented that convention. If it was invented for the Programming Ruby book, that would be either Dave Thomas or Andy Hunt, but I kind of doubt that. The book came out in 2001, Ruby started in 1993, how were they referring to methods before then?
From the rdoc docs (emphasis mine):
Names of classes, source files, and
any method names containing an
underscore or preceded by a hash
character are automatically
hyperlinked from comment text to their
description.
The hash notation was introduced "Programming Ruby - The Pragmatic Programmer's Guide" first published in December 2000.
The "Preface" contains "Notational Conventions":
Within the text, Fred#doIt is a reference to an instance method (doIt) of class Fred, while Fred.new [In some other Ruby documentation, you may see class methods written as Fred::new. This is perfectly valid Ruby syntax; we just happen to feel that Fred.new is less distracting to read.] is a class method, and Fred::EOF is a class constant.
This is clarified in the 2nd edition, published in October 2004:
Within the text, Fred#do_something is a reference to an instance method (in this case do_something) of class Fred, Fred.new is a class method, and Fred::EOF is a class constant. The decision to use a hash character to indicate instance methods was a tough one: it isn’t valid Ruby syntax, but we thought that it was important to differentiate between the instance and class methods of a particular class. When you see us write File.read, you know we’re talking about the class method read. When instead we write File#read, we’re referring to the instance method read.
Ruby itself uses this notation:
> rvm use 1.9.3
Using ruby-1.9.3-p551
> Object.instance_method(:initialize)
=> #<UnboundMethod: Object(BasicObject)#initialize>
It was introduced and formalised by Matz in February 2002:
commit 8210c254bee19294af67bcee0e8f5e02ebb39a60
Author: matz <matz#b2dd03c8-39d4-4d8f-98ff-823fe69b080e>
Date: Tue Feb 5 07:56:31 2002 +0000
* io.c (fptr_finalize): should raise error when fclose fails.
* eval.c (method_inspect): proper output format to distinguish
methods and singleton methods.
git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk#2046 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
All the answers above you list are correct. The one thing I would add is that the documentation style you said you would perfer
Class.method
would be easily confused with class methods. Since you can call class methods in ruby using the above syntax:
class Foo
def self.say_hi
puts "hi"
end
end
Foo.say_hi # => prints "hi"
This was mentioned in the JS version of this question, but it seems likely this nomenclature came from JavaDoc where the hash mark is translated directly into an on-page reference, e.g. href="Component.html#getComponentAt(int, int)"
heff's answer (which I can't comment on due to lack of reputation), that Ruby followed JavaDoc's example, is the best guess in my view. The JavaDoc designers needed or wanted a way to distinguish package qualifiers (which they used the dot for) from class qualifiers (which they used the hash for). JavaDoc's #see and #link tags syntax looks like this:
#see package.class#member [optional label]
{#link package.class#member [optional label]}
See the documentation of JavaDoc's package.class variant of the #see tag and the documentation of JavaDoc's #link tag, which heff already pointed to.
In JavaDoc, the package name can often be omitted, so that only the Class#member part remains, which looks equally strange as in Ruby, because Java code uses the Class.member syntax,
just as Ruby does.
It would be interesting to find out why the JavaDoc designers needed the differing syntax, while the Java compiler does fine with dots for both purposes.

Resources