Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/webpack/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/google-maps/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 应用所有散列';如果可以,请将s值转换为整数_Ruby - Fatal编程技术网

Ruby 应用所有散列';如果可以,请将s值转换为整数

Ruby 应用所有散列';如果可以,请将s值转换为整数,ruby,Ruby,如果像“123”这样的值可以是123 如果值为abc,则将其保留为原始值 buy_house_params.each { |key, value| buy_house_params[key]=value.to_i } 但我仍然得到字符串类型的整数 {"user_id"=>"", "age"=>"28", "gender"=>"male", "monthly_income"=>"48000"} 试试这个: class String def is_number?

如果像“123”这样的值可以是
123

如果值为abc,则将其保留为原始值

buy_house_params.each { |key, value| buy_house_params[key]=value.to_i } 
但我仍然得到字符串类型的整数

{"user_id"=>"", "age"=>"28", "gender"=>"male", "monthly_income"=>"48000"}
试试这个:

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}

它将测试每个hashmap值是否为数字,然后再将其转换为整数。

只有当字符串与所需格式匹配时,才可以使用常规表达式解析字符串:带引号的整数

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

或者您可以测试它是否为整数:

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

Rails会根据activemodel信息自动将字符串解析为整数,如果您担心的话。