user10111321
user10111321

Reputation:

How to convert any String value into its proper representation?

I would like to implement a method that converts any given String value into its proper representation. Here are some examples of what I am referring to:

I believe this has been solved by the code that I have provided, although I am not very pleased with how it looks. I think this could be reworked into something more sophisticated, but my creativity has reached its limit.

def convert(value)
    return true if value =~ /^true$/i
    return false if value =~ /^false$/i
    return value unless value =~ /^[0-9]*$/

    begin
        Integer(value)
    rescue ArgumentError
        nil
    end
end

My question is essentially: Is there a way to provide the same functionality but with fewer return statements and overall less code?

Upvotes: 2

Views: 96

Answers (2)

Arkku
Arkku

Reputation: 42129

In general, case is a decent replacement for multiple ifs.

def convert(str)
  case str.downcase
  when /\A[+-]?[0-9]+\z/
    str.to_i
  when 'true'
    true
  when 'false'
    false
  when ''
    nil
  else
    str.clone
  end
end

Note: only integers in decimal are currently supported (the code in the question also supports octal, but it is unknown whether that is intentional or not). Change the regular expression as needed (and switch back to Integer(str)) if other bases indicated by the 0, 0x, and/or 0b prefixes are desired.

Upvotes: 1

Garrett Motzner
Garrett Motzner

Reputation: 3230

YAML.load may work for your use case, but it is more powerful than you need, and can introduce security holes if you are parsing untrusted data.

It will parse numbers, booleans, and strings just fine, but also has syntax for arrays and hashes, and can load arbitrary object types which can cause arbitrary code execution...

Upvotes: 0

Related Questions