Ruby 1.9 Syntax Änderungen

Der Versionswechsel zu Ruby 1.9 hat auch einige Änderungen in der Syntax mit sich gebracht, siehe CHANGELOG und Wikipedia:

http://en.wikipedia.org/wiki/Ruby_(programming_language)#Ruby_1.9

Zitat: „Ruby 1.9
Ruby 1.9 was released in December 2007. The latest stable version of the reference implementation is 1.9.3 and is dual-licensed under the Ruby License and a BSD License. Adoption of 1.9 was slowed by changes from 1.8 which required many popular third party gems to be rewritten.
Ruby 1.9 introduces many significant changes over the 1.8 series.[21] Examples:

  • Block local variables (variables that are local to the block in which they are declared)
  • An additional lambda syntax (fun = ->(a,b) { puts a + b })
  • Per-string character encodings are supported
  • New socket API (IPv6 support)
  • require_relative import security“.

Einen kurzen Vortrag darüber findet man unter http://slideshow.rubyforge.org/ruby19.html.

In einer irb session sieht das so aus:

[prettify class="ruby"]
> irb
1.9.3-p194 :001 > ?c # single character strings
 => "c"
1.9.3-p194 :002 > "c"
 => "c"
1.9.3-p194 :003 > 'c'
 => "c"
1.9.3-p194 :004 > '''c'''
 => "c"
1.9.3-p194 :005 > 'cat'[1]
 => "a"
1.9.3-p194 :006 > {'key' => 'value'}
 => {"key"=>"value"}
1.9.3-p194 :007 > {'key' => 'value'}['key']
 => "value"
1.9.3-p194 :008 > [1,2,3].to_s
 => "[1, 2, 3]"
1.9.3-p194 :009 > [1,2,3].join
 => "123"
1.9.3-p194 :010 > "abc".to_sym
 => :abc
1.9.3-p194 :011 > :abc == 'abc'
 => false
1.9.3-p194 :012 > {:a=>"a", :c=>"c", :b=>"b"} # order?
 => {:a=>"a", :c=>"c", :b=>"b"}
1.9.3-p194 :017 > a = 1
 => 1
1.9.3-p194 :018 > b = 2
 => 2
1.9.3-p194 :019 > {a: b}
 => {:a=>2}
1.9.3-p194 :020 > {:a => b }
 => {:a=>2}
1.9.3-p194 :021 > t = 1
 => 1
1.9.3-p194 :022 > [1,2].each {|value; t| t=value*value}
 => [1, 2]
1.9.3-p194 :023 >
[/prettify]

Die neue Hash-Syntax in 1.9 erlaubt eine kompaktere Schreibweise:

[sourcecode language=“ruby“]
def help(hash_args)
hash_args.each do |key, value|
puts "Help for #{key} is #{value}. "
end
end

help(:mom => ‚garden‘, :dad => :car) #
help :mom => ‚garden‘, :dad => :car #
help mom: ‚garden‘, dad: :car # Ruby 1.9 additional syntax
[/sourcecode]

liefert in allen Fällen als Ausgabe:

Help for mom is garden.
Help for dad is car.

Dieser Beitrag wurde unter Web Engineering veröffentlicht. Setze ein Lesezeichen auf den Permalink.