Guest User

Untitled

a guest
Nov 19th, 2018
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.02 KB | None | 0 0
  1. ## Rubies 1.9
  2.  
  3. ## Hashes in Ruby 1.9 is respecting and remembering the order of the keys.
  4.  
  5. >> h = {1 => 2, 3 => 4, 5 => 6}
  6. => {1=>2, 3=>4, 5=>6}
  7.  
  8. >> h.keys
  9. => [1, 3, 5]
  10.  
  11. >> h.values
  12. => [2, 4, 6]
  13.  
  14. ##
  15.  
  16. >> h[7] = 8
  17. => 8
  18.  
  19. >> h
  20. => {1=>2, 3=>4, 5=>6, 7=>8}
  21.  
  22. >> h.keys
  23. => [1, 3, 5, 7]
  24.  
  25. >> h.values
  26. => [2, 4, 6, 8]
  27.  
  28. ##
  29.  
  30. >> h[1] = 20
  31. => 20
  32.  
  33. >> h.keys
  34. => [1, 3, 5, 7]
  35.  
  36. >> h.values
  37. => [20, 4, 6, 8]
  38.  
  39. ## Syntax to write keys as symbol
  40.  
  41. # Instead of (in ruby 1.8):
  42.  
  43. >> h = { :a => 1, :b => 2, :c => 3 }
  44. => {:a=>1, :b=>2, :c=>3}
  45.  
  46. # You can also write (in ruby 1.9):
  47.  
  48. >> h = { a: 1, b: 2, c: 3 }
  49. => {:a=>1, :b=>2, :c=>3}
  50.  
  51. ## How will it be valuable? See:
  52.  
  53. >> class Person
  54. >> attr_accessor :name, :age
  55. >>
  56. ?> def initialize(data)
  57. >> @name, @age = data.values_at(:name, :age)
  58. >> end
  59. >> end
  60. => nil
  61.  
  62. >> david = Person.new(name: "David", age: 50)
  63. => #<Person:0x000001008532b0 @name="David", @age=50>
  64.  
  65. >> puts "#{david.name} is a youthful #{david.age}."
  66. David is a youthful 50.
  67. => nil
Add Comment
Please, Sign In to add comment