Monday, December 6, 2010

Ruby vs. Python

Once upon a time, there lived a girl named Red Ruby Hood with Hash h={:foo => "foo_val", :bar => "bar_val"}. Her mother gave her "quux" variable with value "quux_val" and told to print all this shit to he gand-grandmother, who lived far beyond the forest. Long story short, girl uses String.%:

$ irb
irb(main):001:0> h={:foo => "foo_val", :bar => "bar_val"}
=> {:foo=>"foo_val", :bar=>"bar_val"}
irb(main):002:0> puts "Teh %{foo}, teh %{bar} and teh %{quux}" % h.merge({:quux => "quux_val"})
Teh foo_val, teh bar_val and teh quux_val
=> nil
irb(main):003:0> h
=> {:foo=>"foo_val", :bar=>"bar_val"}

But in the forest girl met Evil Gray Python...

$ python
Python 2.6.6 (r266:84292, Oct  1 2010, 13:15:00)
[GCC 4.4.4 20100726 (ALT Linux 4.4.4-alt3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> h={"foo": "foo_val", "bar": "bar_val"}
>>> print "Teh %(foo)s, teh %(bar)s and teh %(quux)s" % h.update({"quux": "quux_val"})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: format requires a mapping


>>> tmp = h.copy().update({"quux": "quux_val"})
>>> tmp


>>> tmp = h.copy()
>>> tmp.update({"quux": "quux_val"})
>>> tmp
{'quux': 'quux_val', 'foo': 'foo_val', 'bar': 'bar_val'}
>>> print "Teh %(foo)s, teh %(bar)s and teh %(quux)s" % h
Teh foo_val, teh bar_val and teh quux_val


So, the Python ate girl, her mother, her grand-grandmother and all lumbermen...