Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby dynamic "typecasting" using class names stored in a variable

Tags:

ruby

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?

like image 524
Andrew Avatar asked Dec 06 '25 20:12

Andrew


1 Answers

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
like image 179
tadman Avatar answered Dec 08 '25 11:12

tadman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!