Content deleted Content added
→Python: <source lang=Pycon> dictionary comprehensions in Python 2.7 and 3.x |
m →Ruby: <source lang=irb> |
||
Line 1,134:
In Ruby a [[hash table|hash]] is used as follows:
<source lang=
irb(main):001:0> phonebook = {
irb(main):005:1> }
=> {"Sally Smart"=>"555-9999", "John Doe"=>"555-1212", "J. Random Hacker"=>"553-1337"}
irb(main):006:0> phonebook['John Doe']
=> "555-1212"
</source>
Ruby supports hash looping and iteration with the following syntax:
<source lang=
irb(main):007:0> ### iterate over keys and values
irb(main):008:0* phonebook.each {|key, value| puts key + " => " + value}
Sally Smart => 555-9999
John Doe => 555-1212
### iterate keys only▼
J. Random Hacker => 553-1337
=> {"Sally Smart"=>"555-9999", "John Doe"=>"555-1212", "J. Random Hacker"=>"553-1337"}
irb(main):009:0> ### iterate
irb(main):010:0* phonebook.
Sally Smart
John Doe
J. Random Hacker
=> {"Sally Smart"=>"555-9999", "John Doe"=>"555-1212", "J. Random Hacker"=>"553-1337"}
irb(main):012:0* phonebook.each_value {|value| puts value}
555-9999
555-1212
553-1337
=> {"Sally Smart"=>"555-9999", "John Doe"=>"555-1212", "J. Random Hacker"=>"553-1337"}
</source>
|