21 Ruby Tricks You Should Be Using In Your Own Code
rubyinside.com
rubyinside.com
A culture that prizes cleverness over consistency is an evolutionary dead-end, this transcends the merits of the technology.
As an example, you can use Perl-style magic variables in Ruby ($!, $_). But in three years writing Ruby code professionally, I think I've only seen one of these ever used, and only rarely.
IMO metaprogramming is a bigger potential problem than Symbol#to_proc or perlisms. You can override the + operator globally with Ruby, or do any other number of stupid things. But metaprogramming also offers a ton of power (similar to Lisp macros?).
It's pretty bad.
does = is = { true => 'Yes', false => 'No' }
does[10 == 50] => “No”
[$a => $b]->[$a <= $b]
I tend to just say max($a, $b) though.It's nice to read the article for that reason. Hopefully people will realize that you can write horrifyingly bad code in any language. I'm looking forward to the Python edition ;)
Maybe we can start approaching language design rationally when people start realizing that all languages suck big time. Even Ruby. Even Lisp.
This means that, sometimes, I find myself in opposition to the python community for its goals of readability and regularity, but it's a powerful language chalk full of good ideas and one of the most important tribes on the net, so I still use it.
(1) Because it's not doing what I expected. (2) Because I want to do something with it that you didn't forsee.
This is not automatic, but I suggest the possibility is much greater with Ruby than with certain other languages for various reasons, and therefore it is at least worth considering a new idiom in Ruby rather than rejecting it outright.
One of the ways you can make your favourite idiom popular is to blog about it, of course. Or perhaps to write something really popular and use your idiom in it, such as returning() {...} or perhaps Symbol#to_proc.
But #16 is a good one — I like one liners but after reading I looked through the code base in one of my projects and sure enough, explicit true/false was spelled out in methods returning booleans...
(rand < event_prob) ? true : false
Shorter and sweeter...
(rand < event_prob)
As opposed to the hideous...
if event_prob return true else return false end
if __FILE__ == $0
# Do something.. run tests, call a method, etc. We're direct.
end
That works great... until you execute the script via a symlink. % ./blah.rb; ./hah.rb
blah
blah
% cat blah.rb
#!/usr/bin/ruby
if __FILE__ == $0
puts "blah"
end
% ls -F hah.rb
hah.rb@Errrr, oh no wait... it does.