Ruby 1.x only has positional arguments with defaults:
def foo(a, b = nil)z
...
end
You can call this only with arguments that follow the order specified in the definition:
foo(1) # now b is nil
foo(1, 2) # now b is 2
There is also some syntactic sugar to allow a hash table to be appended as the last argument without using braces.
foo(1, x: 42) # now b is {x: 42}
This syntactic sugar has been very nice, but using a hash table has some drawbacks:
Expensive: hash table is built at runtime.
Memory-inefficient: hash table must be allocated, and with Ruby objects clocking in at several hundred bytes, it's a lot of unnecessary stuff for something that stays around for a very short while.
There is no way to know if the passed-in hash table was a literal or not (if it's a literal then the called method can safely modify it without copying it first, which is faster).
There is no way to specify, as part of the method definition, what keys are supported. Therefore, you have to put that in the documentation, and then perform runtime assertions.
There is no way to specify defaults for keys. You have to look up the key in the hash table, and then insert a default if it's missing. So you get a lot of "||" or "||=" operations, which are also slow.
Promotes laziness, in that devs will let a method take an "options" hash table and then pass it on to other methods, perhaps after modifying it first by adding or deleting keys.
Old style:
def convert(file_name, options = {})
options.assert_valid_keys(:format, :quality) # from the "activesupport" gem
format = options[:format] || 'jpeg'
converter = SomeKindOfImageConverter.new
converter.load(file_name)
return converter.convert(to_format: format, compression: quality)
end
convert("my_image.png", quality: 0.7)
convert("my_image.png", quality: 0.7, foo: 3) # Caught by assertion
convert("my_image.png", format: "tiff")
Edit: Apparently Ruby 2.0 implements keyword arguments as a hash table internally, which sucks, and means that my first two bullet points remain. Hopefully the implementation will get better.
38
u/TikiTDO Feb 24 '13 edited Feb 24 '13
May I be the first to say, "Holy shit, about time." Also, does anyone have an English translation of the Flonum paper? I'd be really grateful.