Although I’ve been using Ruby 1.9 for a while, I only recently discovered the newer hash syntax that’s now supported:
settings = {
host: "localhost",
port: 5984
}
As opposed to:
settings = {
"host" => "localhost"
}
I like its similarity to JavaScript’s object noation, and looks a bit like JSON, so I’ll probably switch to using it with all my libraries, but I still want to support other users and my own projects which assume the old syntax.
So it really comes down to a fairly simple question of having to test for both symbols and strings. Is there an easy way to do both of these lines as one?
return true if settings["host"] and settings["db"]
return true if settings[:host] and settings[:db]
Even in Ruby < 1.9, you could use symbols for keys. For example:
Ruby 1.9 changes the way that you create hashes. It takes the key and converts it to a symbol for you, while eliminating the need for a hash rocket.
In both cases, if I try to access
settings[:name]withsettings["name"], I’m going to get nil. All Ruby 1.9 does is allow for a new way of creating hashes. To answer your question, you cannot, as far as I know, use the new{key: value}syntax if you want backwards compatibility with Ruby 1.8.