Java Map and Ruby Hash
Java has several implementations of Maps, which are collections that manage key/value pairs. One such collection is the environment variables. Here, then, is a simple program that enumerates the environment variables:
Download code/java_xt/src/PrintEnv.java
import java.util.*;
public class PrintEnv {
public static void main(String[] args) { Map map = System.getenv();
for (Iterator it = map.entrySet().iterator(); it.hasNext();) { Map.Entry e = (Map.Entry) it.next();
System.out.println(String.format("%s: %s", e.getKey(), e.getValue()));
Here is the Ruby equivalent:
Download code/rails_xt/sample_output/hashes.irb
irb(main):032:0> ENV.each {|k,v| puts "#{k}: #{v}"}
TERM_PROGRAM: Apple_Terminal TERM: xterm-color SHELL: /bin/bash
ANT_HOME: /users/stuart/java/apache-ant-1.6.2 ...lots more...
Ruby sets ENV to the environment variables. After that, iteration proceeds with each. This time, the block takes two parameters: k (key) and v (value). Blocks are a completely general mechanism and can take any number of arguments. Functions that use blocks for iteration tend pass one or two parameters to the block, as you have seen.
Most Ruby objects that manage key/value pairs are instances of Hash. Like arrays, hashes have a literal syntax:
irb(main):037:0> dict = {:do => "a deer", :re => "a drop of golden sun"}
=> {:do=>"a deer", :re=>"a drop of golden sun"}
irb(main):037:0> dict = {:do => "a deer", :re => "a drop of golden sun"}
=> {:do=>"a deer", :re=>"a drop of golden sun"}
Curly braces introduce a hash. Keys and values are separated by =>, and pairs are delimited by commas. You can get and set the values in a hash with the methods fetch and store:
irb(main):014:0> dict.store(:so, "a needle pulling thread")
=> "a needle pulling thread"
But Ruby programmers prefer to use the operators [ ] and [ ]=:
irb(main):015:0> dict[:so] => "a needle pulling thread" irb(main):016:0> dict[:dos] = "a beer"
The [ ] and [ ]= operators are easy to remember, because they borrow from mathematical notation. They are also more compact than the named methods fetch and store.
Post a comment