Three New things in Ruby 1.9.x

Surendran Sukumaran

42 sec read

There are lot more things improved in Ruby 1.9.2, I am going to discuss about 3 new things I liked which is introduced in Ruby 1.9.x.
Block Variable Scope in Ruby 1.9.x
Block arguments don’t clash with local variables, arguments are always local.
This is a nice fix in Ruby 1.9 .

Ruby 1.8
[source=’ruby’]
check_block = 2
check_block
=> 2
[/source]
[source=’ruby’]
1.upto(5) {|check_block| check_block}
check_block
=> 5
[/source]
Checkout the value of local variable changed to 5, which is clash with the block variable.
Ruby 1.9
[source=’ruby’]
check_block = 2
check_block
=> 2
[/source]
1.upto(5) {|check_block| check_block}
check_block
=> 2
Here the value of check_block is still 2.
New lambda syntax in Ruby 1.9
[source=’ruby’]
lambda =->(a, b){a + b}
lambda.(1,3)
=> 4
[/source]
We can even call the lambda function like
[source=’ruby’]
lambda[2,4]
=> 6
[/source]
It is also possible to give default values for arguments.
[source=’ruby’]
lambda =->(a, b = 10){a + b}
lambda.(1)
=> 11
[/source]
note : Ruby 1.9.2 still supports the older lambda syntax.
New hash Literal
Alternate syntax for Symbol => Object hash notation:
Ruby 1.8
[source=’ruby’]
{:symbol => 10}
=> {:symbol => 10}
[/source]
Ruby 1.9
[source=’ruby’]
{symbol: 10}
=> {:symbol => 10}
[/source]
I will get back to you soon with some additional new things that was in Ruby 1.9.2 .

Related posts:

3 Replies to “Three New things in Ruby 1.9.x”

Leave a Reply

Your email address will not be published. Required fields are marked *