Skip to content

Commit 35cc9cf

Browse files
committed
Add 14: "Meeting some Locals"
1 parent d945fa9 commit 35cc9cf

1 file changed

Lines changed: 39 additions & 0 deletions

File tree

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
---
2+
title: Meeting some Locals
3+
date: 2015-05-14
4+
tags: syntax, regex
5+
---
6+
7+
There are two very different ways to create local variables in Ruby. You are probably familiar with the classical way:
8+
9+
a, b = "$", "€"
10+
a # => "$"
11+
b # => "€"
12+
13+
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:
14+
15+
%r<(?'a'.)(?'b'.)>=~"$" "€"
16+
a # => "$"
17+
b # => "€"
18+
19+
20+
This implicit creation of local variables is not recommended, because obviously, it violates **PrOWCoFoHuNoMa** (Principle of writing code for humans, not machines).
21+
22+
By the way, this will not work, when you swap operands:
23+
24+
"$" "€"=~%r<(?<a>.)(?<b>.)>
25+
a # NameError: ...
26+
27+
## One More Option
28+
29+
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:
30+
31+
a = nil
32+
binding.local_variable_set :a, "$"
33+
binding.local_variable_set :b, "€"
34+
a # => "$"
35+
b # NameError: ...
36+
37+
## Resources
38+
- [RDoc: Regexp#=~](http://ruby-doc.org/core-2.2.2/Regexp.html#method-i-3D-7E)
39+
- [RDoc: Binding#local_variable_set](http://ruby-doc.org/core-2.2.2/Binding.html#method-i-local_variable_set)

0 commit comments

Comments
 (0)