0

I want to get the buy_house_params, if values like "123" can be 123

if value is abc then keep it as original.

buy_house_params.each { |key, value| buy_house_params[key]=value.to_i } 

But I still get the string type integer

{"user_id"=>"", "age"=>"28", "gender"=>"male", "monthly_income"=>"48000"}
user3675188
  • 7,271
  • 11
  • 40
  • 76

2 Answers2

0

Try this:

class String
  def is_number?
    true if Float(self) rescue false
  end
end

buy_house_params = {"user_id"=>"", "age"=>"28", "gender"=>"male", "monthly_income"=>"48000"}
buy_house_params.each{|k, v| buy_house_params[k] = v.to_i if v.is_number? }
=> {"user_id"=>"", "age"=>28, "gender"=>"male", "monthly_income"=>48000}

It will test to see if each hashmap value is numeric before converting it to an integer.

Martin Konecny
  • 57,827
  • 19
  • 139
  • 159
0

You can use a regular expresion parse the string only if it matches the desired format: quoted integers.

class String
    def is_i?
       !!(self =~ /\A[-+]?[0-9]+\z/)
    end
end

Answered here:

Test if a string is basically an integer in quotes using Ruby?

Or you can test if it's an integer:

>> Integer "1"
=> 1
>> Integer "one"
ArgumentError: invalid value for Integer(): "one"

Ruby: checking if a string can be converted to an integer

Community
  • 1
  • 1
Jorge de los Santos
  • 4,583
  • 1
  • 17
  • 35