Ruby中如何从循环迭代方法中更清晰地返回结果?

2026-04-11 17:111阅读0评论SEO基础
  • 内容介绍
  • 文章标签
  • 相关推荐

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

Ruby中如何从循环迭代方法中更清晰地返回结果?

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

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

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

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

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

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

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

Ruby中如何从循环迭代方法中更清晰地返回结果?

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}}

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

Ruby中如何从循环迭代方法中更清晰地返回结果?

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

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

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

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

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

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

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

Ruby中如何从循环迭代方法中更清晰地返回结果?

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}}