I'd like to setup a hash like so:
{:a => Float, :b => String}
so that I can use it as a "typecast" filter against another hash. For example:
def parse_hash(input_hash)
output = { :a => Float, :b => String }
input_hash.each do |k,v|
input_hash[k] = output[k](v)
end
end
The idea is, you can do:
Float("123") #=> 123.0
but unfortunately, you can't do:
f = Float
f("123") #=> NoMethodError: undefined method `f' for main:Object
...which means the hash parse method I'm going for doesn't work.
So, if I have a reference to a class in a variable, is there any way to get from there to automatically coercing a value to that class?
There's a subtle difference between Float which is a class and Float which is a method. The Ruby interpreter will differentiate on the syntax level, it's based on how you use it. Float("1.0") is a trigger for the method, as is Float "1.0", but a = Float is interpreted as the class.
You need to capture the method specifically:
output = {
a: method(:Float),
b: method(:String)
}
Then later, to call it:
output[:a].call('1.7')
# => 1.7
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With