Hacker News new | past | comments | ask | show | jobs | submit login

Ruby is a heavily idiomatic language. It's strongly advised to use rubocop or a similar style guide -- and to temper that with good judgment, at least when it recommends avoiding `!!`.

In addition to the Pickaxe book, I recommend Metaprogramming Ruby by Paolo Perrotta, and potentially the sequel to that book (which I have yet to read).

Ruby lends itself to a very fluid style. One of the things that you may find less common is explicit variable assignment within a method: most of the time your assignment will be in method signatures and block declarations. The following code is illustrative of technique, but not recommended practice:

  puts(Enumerator.new do |y|
    loop { y.yield Array.new(rand(1..18)) { [*'a'..'z'].sample }.join }
  end.lazy.reject(&IO.readlines('/usr/share/dict/words').method(:include?)).first(10).join(' '))
This generates "non-words", which are guaranteed not to exist in the (Unix) system dictionary, without using explicit assignment. First it creates a (lazy) generator object which yields random "words" of varying length. In Ruby, if you are calling a method with only one argument in an inner loop, you can avoid writing the loop explicitly, which is nice here because it also avoids the performance hit of reading the dictionary file repeatedly. The `method` method lets us pass an object-method pair, to be evaluated later, and the '&' there is a sort of cast-to-block, and you'll see that used in other contexts. So, at that point, we have a lazily-evaluated collection of lazily-filtered strings, and we can take an arbitrary number of these out and print them.

The nice thing about Ruby is that you can probably express what you want in one statement. This does come at the cost of a fair amount of idiom. Some of it is functionally important, some of it is convenient (like using the `*` operator to destructure ranges), and some is pure window dressing, but enforced by convention just the same. The Pickaxe book is better than anything else that I am aware of for describing Ruby idioms. I'm not sure how well it has aged. It's probably recommended to do a lot of pair programming and code review. At times I have mentored others on the website Exercism, and I would recommend that or a similar site.




> The Pickaxe book is better than anything else that I am aware of for describing Ruby idioms. I'm not sure how well it has aged.

The last version covered Ruby 1.9/2.0; the language has evolved since 2.0, so it's certainly not complete and current.


I had decided against a somewhat stronger statement; I didn't want to bash Pickaxe unnecessarily, particularly as I don't have a lot of better suggestions. I'm fairly inclined to write a book myself to address the situation, but not any time soon.




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: