The following returns the default
"client?"
:
class ClientMap
def initialize
@@clients = {"DP000459": "BP"}
@@clients.default = "client?"
end
def get(id)
return @@clients[:id]
end
end
clientMap = ClientMap.new
cKey = "DP000459"
puts clientMap.get(cKey)
Could anybody explain why I cannot retrieve anything but the 'default'?
You've got two problems. First, you are using the symbol syntax in your hash, which works only if your keys are symbols. If you want keys to be strings, you need to use hash-rocket syntax: @@clients = {'DP000459' => 'BP'}
.
Second, your method returns clients[:id]
regardless of what parameter is provided. The key is the symbol :id
rather than the local variable id
. You need to change this to @@clients[id]
.
Here's a cleaned-up version of what you want:
class ClientMap
def initialize
@@clients = {'DP000459' => 'BP'}
@@clients.default = 'client?'
end
def get(id)
@@clients[id]
end
end
I've also taken the liberty of making the spacing more Ruby-idiomatic.
Finally, for variable names in Ruby, use snake_case:
>> client_map = ClientMap.new
>> c_key = 'DP000459'
>> client_map.get(c_key)
#> "BP"