简体   繁体   English

如何将以下内容转换为数组或哈希?

[英]How to convert the following into array or hash?

a=b&c=d&e=f&g=h

How to extract this into [a,b,c,d,e,f,g,h] 如何将其提取到[a,b,c,d,e,f,g,h]

I know I can use split, but it looks like it can only use only one delimit. 我知道我可以使用split,但是看起来只能使用一个定界符。

or how to convert into a hash? 或如何转换为哈希?

split FTW (ie the most straightforward, simple way of doing this is): 拆分FTW(即最简单,最简单的方法是):

irb(main):001:0> s = "a=b&c=d&e=f&g=h"
=> "a=b&c=d&e=f&g=h"
irb(main):002:0> s.split(/[=&]/)
=> ["a", "b", "c", "d", "e", "f", "g", "h"]

Other interesting ways of abusing Ruby: 滥用Ruby的其他有趣方式:

irb(main):001:0> s = "a=b&c=d&e=f&g=h"
=> "a=b&c=d&e=f&g=h"
irb(main):002:0> s.split('=').collect{|x| x.split('&')}.flatten
=> ["a", "b", "c", "d", "e", "f", "g", "h"]
irb(main):003:0> ['=','&'].inject(s) {|t, n| t.split(n).join()}.split('')
=> ["a", "b", "c", "d", "e", "f", "g", "h"]

Also check Cary's and GamesBrainiac's answers for more alternatives :) 还可以查看Cary和GamesBrainiac的答案以获取更多替代方法:)

You can make a hash very easily with something like this: 您可以使用以下内容轻松进行哈希:

myHash  = {} 
strSplit = "a=b&c=d&e=f&g=h".split("&")
for pair in strSplit
   keyValueSplit = pair.split("=")
   myHash[keyValueSplit[0]] = keyValueSplit[1]
end

myHash will look like this in the end {"a"=>"b", "c"=>"d", "e"=>"f", "g"=>"h"} myHash最终看起来像这样{"a"=>"b", "c"=>"d", "e"=>"f", "g"=>"h"}

@Mirea's answer is best, but here's another: @Mirea的答案是最好的,但这是另一个:

s = "a=b&c=d&e=f&g=h"

s.scan /[a-z]/
  #=> ["a", "b", "c", "d", "e", "f", "g", "h"] 

The regex could of course be adjusted as required. 正则表达式当然可以根据需要进行调整。 For example: 例如:

"123a=b&c=d&E=f&g=h".scan /[A-Za-z0-9]/
  #=> ["1", "2", "3", "a", "b", "c", "d", "E", "f", "g", "h"] 

or 要么

"1-2-3a=$b&c=d&e=f&g=h".scan /[^=&]/
  #=> ["1", "-", "2", "-", "3", "a", "$", "b", "c", "d", "e", "f", "g", "h"]

and so on. 等等。

If strings of characters are desired just append + to the character class: 如果需要字符串,只需在字符类后面加上+即可:

"123a=b&ccc=d&E=f&gg=h".scan /[A-Za-z0-9]+/
  #=> ["123a", "b", "ccc", "d", "E", "f", "gg", "h"] 

If the string has the alternating form shown in the example, these work as well: 如果字符串具有示例中所示的交替形式,则它们也可以工作:

(0..s.size).step(2).map { |i| s[i] }
  #=> ["a", "b", "c", "d", "e", "f", "g", "h"]

s.each_char.each_slice(2).map(&:first)
  #=> ["a", "b", "c", "d", "e", "f", "g", "h"] 

I would use is gsub . 我会用的是gsub

irb(main):001:0> s = "a=b&c=d&e=f&g=h"
=> "a=b&c=d&e=f&g=h"
irb(main):004:0> s.gsub(/[\=\&]/, " ").split()
=> ["a", "b", "c", "d", "e", "f", "g", "h"]

So, what we're doing here is replacing all occurrences of = and & with a single space. 因此,我们在这里所做的是用一个空格替换所有出现的=& We then simply split the string. 然后,我们简单地split字符串。

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

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