Ruby 应用所有散列';如果可以,请将s值转换为整数
如果像“123”这样的值可以是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
如果值为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信息自动将字符串解析为整数,如果您担心的话。