Skip to content


Add 14: "Meeting some Locals"
Browse files Browse the repository at this point in the history
  • Loading branch information
janlelis committed May 14, 2015
1 parent d945fa9 commit 35cc9cf
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions source/posts/
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
title: Meeting some Locals
date: 2015-05-14
tags: syntax, regex

There are two very different ways to create local variables in Ruby. You are probably familiar with the classical way:

a, b = "$", "€"
a # => "$"
b # => "€"

It is simple to understand and looks good. But Ruby would not be Ruby, if there weren"t for more obscure ways to assign variables: You could rewrite the previous example to create local variables in a more subtle way:

%r<(?'a'.)(?'b'.)>=~"$" "€"

This comment has been minimized.

Copy link

scooter-dangle May 29, 2015

Is this supposed to look extra obfuscated? If not, why not replace with

/(?'a'.)(?'b'.)/ =~ "$€"


This comment has been minimized.

Copy link

janlelis May 29, 2015

Author Owner

Yes, it is a little more obfuscated than necessary. Do you think it distracts too much from the actual thing to demonstrate?

This comment has been minimized.

Copy link

scooter-dangle via email May 29, 2015

a # => "$"
b # => "€"

This implicit creation of local variables is not recommended, because obviously, it violates **PrOWCoFoHuNoMa** (Principle of writing code for humans, not machines).

By the way, this will not work, when you swap operands:

"$" "€"=~%r<(?<a>.)(?<b>.)>
a # NameError: ...

## One More Option

There is also a third way to set local variables: binding's `local_variable_set`, but it does not really count, since you cannot introduce new variables this way:

a = nil
binding.local_variable_set :a, "$"
binding.local_variable_set :b, "€"
a # => "$"
b # NameError: ...

## Resources
- [RDoc: Regexp#=~](
- [RDoc: Binding#local_variable_set](

0 comments on commit 35cc9cf

Please sign in to comment.