Russell
Russell

Reputation: 12439

Cast string to type known only at runtime?

I'm new to Ruby so this may be a stupid question. I know that, for example, if I want to convert a String to a Float I can simply call to_f.

However, what if I only know the type I want to convert to at runtime? So for example I would be able to write something like:

klass = Float
converted = klass.from_s '10.25'

Is there such a method that I just haven't found? Obviously it wouldn't work for everything but at least for basic number types.

Upvotes: 0

Views: 98

Answers (1)

Michael Kohl
Michael Kohl

Reputation: 66837

Since you only want to cover some basic number types, this would work:

conversions = { Float => :to_f, Fixnum => :to_i }
klass = Float
converted = '10.25'.send(conversions[klass]) #=> 10.25
klass = Fixnum
converted = '10.25'.send(conversions[klass]) #=> 10

Another thing that works is using the Kernel#Float and Kernel#Integer methods like this:

>> send(klass.to_s.intern, '10.25')
=> 10.25
>> klass = Integer
=> Integer
>> send(klass.to_s.intern, '10.25')
ArgumentError: invalid value for Integer: "10.25"
    from (irb):25:in `Integer'
    from (irb):25:in `send'
    from (irb):25
    from :0
>> send(klass.to_s.intern, '10')
=> 10

Upvotes: 3

Related Questions