我们如何实现“就地”转换为哈希值的浮点数?动机是不必写这样的代码
r['delivery_fee'] = r['delivery_fee'].to_f
r['delivery_free_over'] = r['delivery_free_over'].to_f
r['delivery_possible_over'] = r['delivery_possible_over'].to_f
r['delivery_range'] = r['delivery_range'].to_f
Run Code Online (Sandbox Code Playgroud)
反而
to_f r['delivery_fee']
to_f r['delivery_free_over']
# ...
Run Code Online (Sandbox Code Playgroud)
我这样做了,但是它没有按预期的方式工作。
def to_f(s)
s = s.to_f
end
data = "1"
p data # => "1"
to_f data
p data # => Still "1" and not float
Run Code Online (Sandbox Code Playgroud)
这很容易:
h = { one: '1', two: '2' }
Hash[h.keys.zip(h.values.map(&:to_f))]
# => { :one => 1.0, :two => 2.0 }
# or
Hash[h.map {|k, v| [k, v.to_f] }]
# => { :one => 1.0, :two => 2.0 }
Run Code Online (Sandbox Code Playgroud)
确实,使用这两个选项中的哪一个是优先选择的问题。