Genadi Samokovarov

Code.

Read this first

Ruby Tips & Tricks #2: Lambda Literals in 1.9.3

Ruby 1.9.3 support is coming to an end and with it — an end of a syntax limitation. Welcome to the second Ruby Tips & Tricks post.

Have you ever wondered why the community style guide suggest you to write lambda literals like ->(a, b) { a + b } instead of -> (a, b) { a + b }? Well, there is a bit more than aesthetics to it…

In Ruby 1.9.3 -> (a, b) { a + b } isn’t syntactically valid:

>> -> (a, b) { a + b }
SyntaxError: (irb):1: syntax error, unexpected tLPAREN_ARG, expecting keyword_do_LAMBDA or tLAMBEG
-> (a, b) { a + b }
    ^
    from /1.9.3-p545/bin/irb:12:in `<main>'

The fore mentioned expression is valid in Ruby 2.0.0 and above. That’s what I call a significant whitespace!

Have you ever been bitten by it? Drop me a line on twitter at @gsamokovarov.

Continue reading →


Ruby Tips & Tricks #1: Procs with Empty Blocks

Hello and welcome to the first Ruby Tips & Tricks post. In this series I would talk about interesting bits in Ruby.

Let’s start the series with a documented, but little known feature of the Proc.new constructor.

When Proc.new is called in a method with attached block, that block will be converted to a Proc object. Sounds confusing? An example shows it best:

def proc_from
  Proc.new
end

proc = proc_from { "hello" }
proc.call  #=> "hello"

When I first ran into code like this, it took me a while to digest it, even though this behaviour is noted pretty early in the Proc documentation.

Now that we know that it exists, how do we use it? Is it better than the more conventional example:

def proc_from(&block)
  block
end

proc = proc_from { "hello" }
proc.call  #=> "hello"

I believe it is! Why? In the conventional example, if there is no block given, block is nil. This contributes to

Continue reading →