Ruby syntax trivia

18 Dec 2013

The last time I wrote Ruby among Rubyists was almost a year ago, so forgive me if some or all of these have become common knowledge since then. But most folks I've talked to seem not to know about them.

Character syntax

Ruby doesn't have a character datatype, but it does have a special syntax for one-character strings:

puts ?a          # => a
puts ?\s.inspect # => " "

How I learned about it: saw it in the source code for Camping.

Syntactic sugar for #call

For those times when your really wish Ruby treated methods and procs the same way:

x = lambda {|a, b| a+b}
x.(1, 2) # 3

How I learned about it: accidentally typed a period in front of some parentheses when calling a method in a REPL and got a NoMethodError for call.

Stabby lambdas and BasicObjects

Lots of folks know about stabby lambdas, but they have an interesting extra use case:

class Glub < BasicObject
  def this_works
    -> {1} # works because stabbies are syntactic gizmos, not method calls

  def this_doesnt
    lambda {1} # fails because lambda is a method on the Kernel module,
  end          # which BasicObject does not include.

How I learned about it: once wrote a testing library based on BasicObject delegators and was surprised to find that it broke when I changed some stabby lambdas to, uh, lambda lambdas.

Flexible string delimiters

Ruby lets you use different non-alphanumeric delimiters for string literals by prefixing your data with a %:

%[hello world]                  # "hello world"
%%also an acceptable delimiter% # "also an acceptable delimiter"

Since % is also a method on String for printf-style interpolation, that means any sequence of 4n + 3 percent signs (for integer n) is a valid Ruby expression that evaluates to the empty string:

%%%%%%%%%%%%%%%%%%% # ""

How I learned about it: an old boss showed me. Thanks L!