【问题标题】:How to get a value in a multidimensional array?如何获取多维数组中的值?
【发布时间】:2012-02-20 20:11:40
【问题描述】:

我正在使用 Rails 3.1.0,我想从多维数组中获取特定值。也就是我有以下

array = [ ['Text1', 's1'], ['Text2', 's2'], ['Text3', 's3'] ]

例如,我想在上面的数组中搜索字符串s3,以便得到对应的值Text3s1 相同,所以得到 Text1s2,所以得到 Text2

我怎样才能做到这一点?

【问题讨论】:

标签: ruby-on-rails ruby arrays ruby-on-rails-3 multidimensional-array


【解决方案1】:

对于较小的数组和不频繁的查找,您可以保留该数组:

array = [ ['Text1', 's1'], ['Text2', 's2'], ['Text3', 's3'] ]
p array.rassoc('s3').first #=> 'Text3'

【讨论】:

  • +1,哇,以前从未见过这种方法......有什么特别的原因会包含它吗?因为我从来没有见过像这样的实际有用的案例。
猜你喜欢
  • 1970-01-01
  • 2017-10-26
  • 1970-01-01
  • 2012-05-03
  • 2021-11-01
  • 2015-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多