4 ms·
1.day.ago is idiomatic Ruby code because 1.class.methods will give a long list of methods supported by `1` This is because in Ruby everything* is an objec
by gls2ro 5y ago
1.day.ago is idiomatic Ruby code because
1.class.methods
will give a long list of methods supported by `1`
This is because in Ruby everything* is an object. I agree that from outside Ruby this might look weird, but knowing Ruby this is very simple to understand.
Knowing this you can also expect the following things to work in Rails I think:
1.day.ago + 2.hours
This is because:
+ is an instance method defined on the Integer class. See Integer.instance_methods. So it is more like `1.day.ago.+(2.hours)`
and I expect then that in Rails (or some gem) they added `hours` as a method to the Integer or a compatible object
so in the end this operation is just normal:
object.instance_method.instance_method(object.instance_method)
nothing magic here happening because this is all valid OOP code where an instance method could return a self object let's say.
Knowing this then before writing in a Ruby Interpreter one can find out if that code is in the standard library (see https://ruby-doc.org/core-3.1.0/Integer.html https://ruby-doc.org/core-3.1.0/Integer.html) or in a Gem
- montroser 5y agoI understand how it all works mechanically, I just don't think it models the real world conceptually. OOP works well when you make classes to represent fundamental nouns, those nouns with properties describing their existential makeup. But day.ago is not that -- it's just abusing the syntax to fake a natural looking expression. On finding out where a method came from, I appreciate that I can look to see if it's core or else must be from a gem, but I want to know _which_ gem did it come from.
- gls2ro 5y agoI don't try to convince you to like Ruby, but I don't really understand how you can know in other languages if something comes from a plugin or not by simply looking at it and not knowing the std library or using an IDE. Maybe in the case of a language with a very small standard library, this could be easy: as the best assumption could be that it is in a plugin/module. But I think looking at a piece of code and direct knowing from _which_ plugin some methods comes from has more to do with naming conventions than with the language itself, especially in languages where either overriding or overloading or a form of them is possible. In the case of Ruby, I recommend RubyMine and just to go to definition. 99% of cases it will correctly open the definition from the gem of std library. I agree that in Ruby - maybe more than in other languages - one can really make some behaviors hard to discover. But most of the libraries are straight forward and Rails is very well documented in code. I usually prefer to just go to the definition and read the method than browse the API docs.