rubymri

What's the most official documentation of or way to learn Ruby's syntax?


There's https://ruby-doc.org/docs/ruby-doc-bundle/Manual/man-1.4/syntax.html, by Yukihiro Matsumoto himself, but given that I can't find mention of &. (e.g. a&.b) or &: (e.g. m(&:f)), it doesn't seem very updated. I remember once upon a time there was one person that was trying to document it based on MRI's unit tests, but gave up and abandoned the project because of lack of collaboration from the developers.

Right now, it seems the only way to learn is by stumbling on new syntax by accident on StackOverflow or some open source ruby project.


Solution

  • The canonical documentation of Ruby's syntax is maintained along with with language's source code in the doc/syntax directory. You can read it on GitHub or e.g. on ruby-doc.org.

    There, you will find the description of the &. operator:

    You may use &. to designate a receiver, then my_method is not invoked and the result is nil when the receiver is nil. In that case, the arguments of my_method are not evaluated.

    as well as the logic to convert a Proc object (or more correctly: an object which can be converted to a Proc) to a block:

    You can convert a proc or lambda to a block argument with the & operator:

    argument = proc { |a| puts "#{a.inspect} was yielded" }
    
    my_method(&argument)
    

    Here, the interesting thing to note is that Symbols respond to to_proc which allows Symbols to act like procs (and thus can be converted to a proc and subsequently to a block when used to call a method with e.g. my_method(&:foo).

    In general, to learn about Ruby's syntax and approach to programming, you could start with one of several books, e.g. Programming Ruby 1.9 and 2.0. In general, books tend to take some time (usually a few years) from start to publishing and thus tend to not cover the very latest language additions. However, they can give you a good overview about the language and its core concepts.

    There are some additions in newer versions of Ruby which make some things easier, like the &. operator added in Ruby 2.3 or things like default frozen strings. While these additions are useful, you will usually stumble upon them when you start to actually programming in Ruby. Here, it might then be useful to follow the release news where new features and notable changes are briefly described.