Ruby如何实现循环迭代中的更明确返回值?

更新于
2026-10-09 21:17:17
1阅读来源:SEO资讯
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计319个文字,预计阅读时间需要2分钟。

Ruby如何实现循环迭代中的更明确返回值?

我发现我经常有遍历可枚举的方法,以便返回不同的可枚举或列表。这些方法几乎总是看起来像这个简单的例子:+def+ build_hash(array)+ hash=+{+}+ array.each do |item|+ hash[item[:id]]=item+ end+ hash+ end+ 这种方式。

我发现我经常有遍历可枚举的方法,以便返回不同的可枚举或散列.这些方法几乎总是看起来像这个简单的例子:

def build_hash(array) hash = {} array.each do |item| hash[ item[:id] ]= item end hash end

这种方法有效,但我经常想知道是否有更简洁的方法来执行此操作,特别是无需将循环包装在临时对象中以便返回正确.

有没有人知道改进的和/或更清洁和/或更快的方法,或者这是最好的方式吗?

考虑到您的具体示例,以下是一些方法

arr = [{:id => 1, :name => :foo}, {:id => 2, :name => :bar}] Hash[arr.map{ |o| [o[:id], o] }] arr.each_with_object({}){ |o, h| h[o[:id]] = o } arr.reduce({}){ |h, o| h[o[:id]] = o; h } arr.reduce({}){ |h, o| h.merge o[:id] => o } # each of these return the same Hash # {1=>{:id=>1, :name=>:foo}, 2=>{:id=>2, :name=>:bar}}

Ruby如何实现循环迭代中的更明确返回值?

本文共计319个文字,预计阅读时间需要2分钟。

Ruby如何实现循环迭代中的更明确返回值?

我发现我经常有遍历可枚举的方法,以便返回不同的可枚举或列表。这些方法几乎总是看起来像这个简单的例子:+def+ build_hash(array)+ hash=+{+}+ array.each do |item|+ hash[item[:id]]=item+ end+ hash+ end+ 这种方式。

我发现我经常有遍历可枚举的方法,以便返回不同的可枚举或散列.这些方法几乎总是看起来像这个简单的例子:

def build_hash(array) hash = {} array.each do |item| hash[ item[:id] ]= item end hash end

这种方法有效,但我经常想知道是否有更简洁的方法来执行此操作,特别是无需将循环包装在临时对象中以便返回正确.

有没有人知道改进的和/或更清洁和/或更快的方法,或者这是最好的方式吗?

考虑到您的具体示例,以下是一些方法

arr = [{:id => 1, :name => :foo}, {:id => 2, :name => :bar}] Hash[arr.map{ |o| [o[:id], o] }] arr.each_with_object({}){ |o, h| h[o[:id]] = o } arr.reduce({}){ |h, o| h[o[:id]] = o; h } arr.reduce({}){ |h, o| h.merge o[:id] => o } # each of these return the same Hash # {1=>{:id=>1, :name=>:foo}, 2=>{:id=>2, :name=>:bar}}

Ruby如何实现循环迭代中的更明确返回值?