Hello, I'm interested in hearing what your favorite ruby trick is. I'm a big fan of using inject in new and unique ways. You?
Count me in for another fan of inject. Additionally, I enjoy using Arrays in general for everything I can apply them to. There's a ton of functionality in the Array and Enumerable classes.
I like using the nifty co-routine syntax to build new stuff. That is, the abillity to write a method foo, with a yield in it, and then use syntax like
foo do
code
end
This is used extensively in, eg, rake, to build DSLs.
Hard to choose.
- Using
method_missing
anddefine_method
to produce full featured API's cheaply and easily. - painless memoization:
def funky_filtered_list @ffl ||= @list.find_all { |x| # complex foo here, only run once and only when needed } end
- state modifying methods that return self, letting you write things like
Shape.new.start_at(0,0).line_to(0,10).arc_around(0,0,90.degrees).close.area
- Monkey patching to extend the functionality of all objects
-- MarkusQ
It's really hard to come up with a definitive answer.
I really like mixins, and the ability to monkeypatch stuff. It makes it so easy to extend logic with minimal effort.
I'm also a fan of send.
>> def add(x,y)
>> x + y
>> end
=> nil
>> send "add", 5, 6
=> 11
My current favourite, probably because I'm only just learning how to do it, is using mixin modules to add declarative aspects to classes.
My favorite "trick" is the facile and flexible syntax. Hacks with #inject, #method_missing and etc. often end up as maintenance nightmares. Ruby is elegant so please: use it in elegant ways.
Open objects and classes. Allow you add and change behavior of existing libraries and objects. Can be dangerous sometimes but is generally a cool and useful feature.
Except some other things already mentioned here, I like the fact that everything has a value in Ruby (every statement is an expression).
some_var = case x
when 1: "foo"
when 2: "bar"
else "baz"
end
There is a keyword that is very useful that many people do not use in Ruby - redo . You can actually perform a lot of tricks with this keyword.
Reference: http://www.rubyrailways.com/rubys-most-underused-keyword/
Overriding operators on Fixnum:
class Fixnum
def +(num)
self - num
end
end
All the things you can do with method_missing
are pretty cool too.