简体   繁体   English

如何将字符串中的数字转换为哈希

[英]How to convert numbers in a string, into a hash

给定字符串,例如"ABCD 100" ,将其转换为{"ABCD": 100}的最有效方法是什么,其中"ABCD"是键,而100是整数和值?

If that is the exact format I'd do 如果那是我想要的确切格式

key, value = "ABCD 100".split
{key.to_sym => value.to_i}

If you're looking for a one-liner 如果您正在寻找单线

Since ruby 2.4.0 自红宝石2.4.0

["ABCD 100".split].to_h.each_with_object({}) { |(k, v), memo| memo[k.to_sym] = v.to_i }

From ruby 2.4.0 从Ruby 2.4.0开始

["ABCD 100".split].to_h.transform_values!(&:to_i)

Assuming that you have more than one key-value pair, you can combine split , each_slice and map : 假设您有多个键值对,则可以组合spliteach_slicemap

"ABCD 100 EFG 200".split
                  .each_slice(2)
                  .map {|k, v| [k.to_sym, v.to_i]}.to_h
#=> {:ABCD=>100, :EFG=>200}

Or with scan and groups: 或使用scan和分组:

"ABCD 100 EFG 200".scan(/([A-Z]+)\s([0-9]+)/)
                  .map! {|k, v| [k.to_sym, v.to_i]}.to_h
#=> {:ABCD=>100, :EFG=>200}

Use regex according to your actual issue, it is just an instance. 根据您的实际问题使用正则表达式,它只是一个实例。

If your pattern is string like "key value", you can use String#split. 如果您的模式是“键值”之类的字符串,则可以使用String#split。 It takes a string and returns an Array of substrings delimited by a separator. 它接受一个字符串并返回由分隔符分隔的子字符串数组。 If you don't give a separator, the default one is spaces. 如果不指定分隔符,则默认为空格。

def insert_values_from_string_into_hash(to_be_parsed_string, hash)
  string_key, value = to_be_parsed_string.split
  hash[string_key] = value
  hash
end   

insert_values_from_string_into_hash("ABCD 100", {}) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM