Comparison of programming languages (associative array): Difference between revisions

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=Rubyirb>
irb(main):001:0> phonebook = {
irb(main):002:1* 'Sally Smart' => '555-9999',
irb(main):003:1* 'John Doe' => '555-1212',
irb(main):004:1* 'J. Random Hacker' => '553-1337'
irb(main):005:1> }
}
=> {"Sally Smart"=>"555-9999", "John Doe"=>"555-1212", "J. Random Hacker"=>"553-1337"}
 
irb(main):006:0> phonebook['John Doe']; #produces this -> '555-1212'
=> "555-1212"
</source>
 
Ruby supports hash looping and iteration with the following syntax:
 
<source lang=Rubyirb>
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
phonebook.each_key {|key| puts key}
=> {"Sally Smart"=>"555-9999", "John Doe"=>"555-1212", "J. Random Hacker"=>"553-1337"}
 
irb(main):009:0> ### iterate valueskeys only
irb(main):010:0* phonebook.each_valueeach_key {|valuekey| puts valuekey}
Sally Smart
John Doe
J. Random Hacker
=> {"Sally Smart"=>"555-9999", "John Doe"=>"555-1212", "J. Random Hacker"=>"553-1337"}
irb(main):011:0> ### iterate keysvalues only
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>