【问题标题】:Obtain a set of numbers from a sequence of arrays of strings in ruby从ruby中的字符串数组序列中获取一组数字
【发布时间】:2014-06-23 17:06:58
【问题描述】:

我有一个字符串数组,如下所示

b=["yesterday: 40", "today: 20", "change: +3", "changes_2: 10.00%", "high: 30", "low: 20"]

如何从该数组中获取值 40、20、+3、10.00%、30 和 20 的集合

我已经完成了

 c = b.map {|n| n.split(" ")}

返回

 [["yesterday:", "40"], ["today:", "20"], ["change:", "+3"], ["changes_2:", "10.00%"], ["high:", "30"], ["low:", "20"]]

【问题讨论】:

  • 考虑在数组上使用map,然后在映射块中的每个组件字符串上使用String#split,以提取您想要的内容。
  • 你已经接近了!如您所见,String#split 返回一个数组,因此您可以选择它的特定索引从map 块返回,而不是仅仅聚合从split 返回的所有数组。
  • @ChrisHeald ...我已经按照您所说的进行了映射和拆分。我现在如何提取值,我做了 c.first.last 并得到了 40,但是当我做了 d= c.each{|x| x.last} 我仍然得到 c 返回的相同数组

标签: ruby arrays regex string


【解决方案1】:

只需索引 split 数组,然后在块中返回它:

> c = b.map {|n| n.split(": ")[1]}
=> ["40", "20", "+3", "10.00%", "30", "20"]

【讨论】:

  • 我会使用 .last 而不是索引,但这是个人喜好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-21
  • 1970-01-01
  • 1970-01-01
  • 2018-04-12
相关资源
最近更新 更多