I’m using a rake task to receive and handle data.
The data looks like "code:value" where each code maps to a specific action.
For example, "0xFE:0x47" calls the method corresponding to the 0xFE tag with the parameter 0x47.
For scalability purposes I think this should be mapped to an hash and have the methods defined below:
tags = Hash[0xFA => taskA, 0xFB => taskB, 0xFC => taskC]
def taskA(value)
...
end
def taskB(value)
...
end
def taskC(value)
...
end
then, when a message is received, do a split and call the method on the hash, like:
tokens = message.split(':')
tags[tokens[0]](tokens[1])
Ruby doesn’t like the Hash initialization. What’s the correct way to solve this problem?
Maybe you’re expecting the methods to work like they do in JavaScript, where they’re just references until called, but this is not the case. The best approach is to keep them as symbols and then use the
sendmethod to call them:The
Hash[]initializer is usually reserved for special cases, such as when converting an Array into a Hash. In this case it’s redundant if not confusing so is best omitted.{ ... }has the effect of creating a Hash implicitly.