Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ## Rubies 1.9
- ## Hashes in Ruby 1.9 is respecting and remembering the order of the keys.
- >> h = {1 => 2, 3 => 4, 5 => 6}
- => {1=>2, 3=>4, 5=>6}
- >> h.keys
- => [1, 3, 5]
- >> h.values
- => [2, 4, 6]
- ##
- >> h[7] = 8
- => 8
- >> h
- => {1=>2, 3=>4, 5=>6, 7=>8}
- >> h.keys
- => [1, 3, 5, 7]
- >> h.values
- => [2, 4, 6, 8]
- ##
- >> h[1] = 20
- => 20
- >> h.keys
- => [1, 3, 5, 7]
- >> h.values
- => [20, 4, 6, 8]
- ## Syntax to write keys as symbol
- # Instead of (in ruby 1.8):
- >> h = { :a => 1, :b => 2, :c => 3 }
- => {:a=>1, :b=>2, :c=>3}
- # You can also write (in ruby 1.9):
- >> h = { a: 1, b: 2, c: 3 }
- => {:a=>1, :b=>2, :c=>3}
- ## How will it be valuable? See:
- >> class Person
- >> attr_accessor :name, :age
- >>
- ?> def initialize(data)
- >> @name, @age = data.values_at(:name, :age)
- >> end
- >> end
- => nil
- >> david = Person.new(name: "David", age: 50)
- => #<Person:0x000001008532b0 @name="David", @age=50>
- >> puts "#{david.name} is a youthful #{david.age}."
- David is a youthful 50.
- => nil
Add Comment
Please, Sign In to add comment