Reputation: 9
I can cast a string to float via:
Float("1")
Now I have this:
f = Float
How can I use f
to cast a string to float?
Edited
I'm sorry for not being clear.
Here is my scenario:
I'm using Redis DB, via gem redis-rb. Basically redis-db
stores values as strings. When I map back values from DB to my objects, I wish to cast them to some primitive types for easy to use.
So I use this:
require 'ostruct'
class Person < OpenStruct
MAP = { :name => String, :age => Fixnum }
##
# This reads data from DB, and converts them to some "primitive" types
# for easy use.
#
def read
MAP.each_pair do |sym, cls|
# read data as string from DB, via key `sym.to_s`
s = ...
# now I have `cls`, how can I "cast" `s` to `cls`?
self[sym] = ???
# I know I can "iterate" all types by this:
#
# if cls.is_a? Float
# self[sym] = s.to_f
# elsif cls.is_a? Fixnum
# self[sym] = s.to_i
# ...
#
# But in Python I can just cast `s` to `cls` in one line...
# So I wonder if there is some way to cast `s` to `cls` in Ruby?
end
end # read
end # Person
Saying "for easy use", I mean I want to:
p = Person.new
p.read
# I want to access `age` as an integer, not a string
if p.age +-*/ ...
Upvotes: 0
Views: 111
Reputation: 3721
For what I understood from your question you want this:
result = '1'.to_f #outputs => 1.0
then for string:
result.to_s #outputs => "1.0"
And you can also do it in one step as well:
'1'.to_f.to_s #outputs => "1.0"
For more about strings and ruby you can see ruby doc
Upvotes: 0
Reputation: 168199
You cannot use f
to do it. The Float
in Float("1")
is a method. The Float
in f = Float
is a class (an object). They are different things.
Upvotes: 2