dj.*_*dj. 3 ruby string integer type-conversion
我有从几个不同的XML数据库转储导入的哈希行,看起来像这样(但使用不同的键):
{"Id"=>"1", "Name"=>"Cat", "Description"=>"Feline", "Count"=>"123"}
Run Code Online (Sandbox Code Playgroud)
我尝试使用#to_i但它将非数字字符串转换为0:
"Feline".to_i
# => 0
Run Code Online (Sandbox Code Playgroud)
但我想是一种方式"Feline"仍然是一个字符串,而Id与Count在上面的例子中变得整数1和123.
有一种简单的方法来转换只有字符串值,其数字为整数?
一行答案:使用正则表达式方法
h.merge(h) { |k, v| v.match(/\A[+-]?\d+?(\.\d+)?\Z/) ? v.to_i : v }
Run Code Online (Sandbox Code Playgroud)
使用整数方法
h.merge(h) { |k, v| Integer(v) rescue v }
Run Code Online (Sandbox Code Playgroud)
使用内核#Integer:
my_hash = {"Id"=>"1", "Name"=>"Cat", "Description"=>"Feline", "Count"=>"123"}
Hash[ my_hash.map{ |a, b| [ a,
begin
Integer b
rescue ArgumentError
b
end ] } ]
Run Code Online (Sandbox Code Playgroud)
稍后添加:使用我的y_supportgem,您可以使哈希操作更简洁.
require 'y_support/core_ext/hash'
my_hash.with_values { |v| begin
Integer b
rescue ArgumentError
b
end }
Run Code Online (Sandbox Code Playgroud)
YSupport可通过安装gem install y_support,同时还提供Hash#with_keys,Hash#with_values!,Hash#with_keys!你希望他们做什么,以及做Hash#modify任何需要一个二进制块返回一对值,修改的地方散.有人建议将来将这些方法直接添加到Ruby核心.
| 归档时间: |
|
| 查看次数: |
5607 次 |
| 最近记录: |