【问题标题】:Returning index with value while using each_with_index method使用 each_with_index 方法时返回带值的索引
【发布时间】:2015-07-23 20:29:46
【问题描述】:

用 Ruby 构建一个基本的地址簿。我的程序中有以下代码行,它基于标准数字输入(entrynumber)迭代现有数组(@address_book)以匹配数组索引。然后返回与该索引匹配的结果值。这是有问题的代码:

     puts @address_book.entries.each_with_index.select {|val, i| i == (entrynumber - 1)}

结果看起来不错,除了索引也在底部返回,如下所示:(注意返回末尾的 0)我最好不返回底部的索引号本身。

View by Entry Number
Entry Number: 1
You picked 1
Name: adam adams
Phone Number: 111-111-1111
Email: aa@aa.com
0

在返回值但没有索引方面我缺少什么?

【问题讨论】:

  • 能分享一下address_book类的to_s方法吗
  • 不只是@address_book.entries[entrynumber-1]吗?

标签: ruby


【解决方案1】:

问题

问题是 each_with_index 正在将@address_book.entries 变成一个数组数组。这是我的意思的一个例子:

["a", "b"].each_with_index.to_a
# => [["a", 0], ["b", 1]] 

因此,当您将select 应用到each_with_index 时,每个选定的元素都将是一个包含元素及其索引的数组:

["a", "b"].each_with_index.select { |e, i| i == 1 }
=> [["b", 1]] 

一个错误的修复

您可以通过使用#map 仅选择每个选定行的第一个元素来解决此问题:

["a", "b"].each_with_index.select { |e, i| i == 1 }.map(&:first)
 => ["b"] 

使用 select.with_index

更好的是,您可以使用 select.with_index:

["a", "b"].select.with_index { |e, i| i == 1}
 => ["b"] 

或者,对于您的代码:

@address_book.entries.
  each_with_index.select.with_index {|val, i| i == (entrynumber - 1)}

使用数组#[]

如果@address_book.entries是一个数组,那么你可以index the array,根本不用select:

@address_book_entries[entrynumber - 1]

如果不是数组,你可以用#to_a把它变成一个:

@address_book.entries.to_a[entrynumber - 1]

但是,如果 @address_book.entries 很大,这可能会占用大量内存。将枚举转换为数组时要小心。

【讨论】:

    【解决方案2】:

    看起来您希望它获得一个项目,而这并不是select 最适合的项目(尤其是当您通过索引检索它时。我可能会这样做:

    @address_book.entries.to_a[entrynumber - 1]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-15
      • 2022-09-25
      • 1970-01-01
      • 1970-01-01
      • 2012-06-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多