Sergio Belevskij
Sergio Belevskij

Reputation: 2947

Ruby type conversion arbitrary by needed class

Example. I have two variables with random classes:

first = 12345    #Fixnum
second = "12345" #String

Can i convert second var to class identical of first variable?

i can do it with if block:

if first.class == Fixnum
 second = second.to_i
elsif first.class == String
 # do nothing
end

but, can a do it simple, instead if or case constructions?

Upvotes: 1

Views: 72

Answers (1)

Simone Carletti
Simone Carletti

Reputation: 176402

You can use a case statement.

result = case first
  when Fixnum
    second.to_i
  when Array
    [second]
  else
    second
end

However, if you start to have several values, you may want to consider a better design pattern. For example, you can wrap second in custom object types that properly implement a casting technique.

result = first.class.cast(second)

Upvotes: 2

Related Questions