Tag: 可枚举

Rails – Enumerable Group_By多个关联

我想通过他们有许多关系对一组对象进行分组……就像这样 s.inventoryitems.group_by{|i| i.locations} 为了简单起见,这返回给我这样的东西: {[1, 2, 3]=>[“a”], [2]=>[“b”, “c”], []=>[“d”]} 我正在寻找这样的结果: {[1] => [“a”], [2] => [“a”,”b”,”c”], [3] => [“a”], [] => [“d”]} 我正在努力重组事情所以这一切都可以用更直观的DB和模型关联方式完成,但与此同时我需要立即实现这个并且需要用一些Ruby来解决它并且我不确定。 谢谢你的帮助!

Ruby:要散列的数组,没有任何局部变量

我有一个字符串数组。 array = [“foo”,”bar”,”baz”] 我正在尝试将其转换为以下内容: {“foo”=>nil, “bar”=>nil, “baz” => nil} 我一直用以下方法做到这一点: new_hash = {} array.each { |k| new_hash[k] = nil } new_hash 我想知道是否有任何方法可以在单行/没有任何实例变量的情况下实现这一点。

Ruby Enumeration:首先取n,其中block返回true

我想获取通过块的第一个“n”条目 a = 1..100_000_000 # Basically a long array # This iterates over the whole array — no good b = a.select{|x| x.expensive_operation?}.take(n) 一旦我得到“昂贵”条件为真的n个条目,我想要将迭代短路。 你有什么建议? take_while并保持n的计数? # This is the code i have; which i think can be written better, but how? a = 1..100_000_000 # Basically a long array n = 20 i = […]

为什么在Enumerable模块中定义了Range#sum?

在Ruby 2.4和Integer Ranges中, Range(Enumerable)#sum被优化为直接返回结果,而不迭代所有元素。 我不明白为什么在enum.c为Enumerable模块定义了相应的代码,而在range.c没有在range.c定义。 为什么Enumerable应该知道包含它的类(例如Range , Hash ,…)并检查它们的类型而不是让这些类覆盖Enumerable#sum ? 见于enum.c : return int_range_sum(beg, end, excl, memo.v); # or hash_sum(obj, &memo);

为什么Enumerable在Ruby中没有length属性?

至少在Ruby 1.9.3中, Enumerable对象没有length属性。 据我所知,任何Enumerable都是一个集合,如sort和find_index等方法所certificate。 一个集总是有一个定义明确的长度(……对吗?),为什么这不是一个属性?

Ruby Enumerables – 它们究竟是什么?

有人可以用最基本的术语解释Ruby Enumerable是什么吗? 我对编码很新,只是开始使用数组和哈希。 我到处都读到“Enumerables”这个词,但我不明白它们是什么。

Ruby计数字符序列不使用正则表达式

在计算序列中的字符时需要有关此代码的帮助。 这就是我要的: word(“aaabbcbbaaa”) == [[“a”, 3], [“b”, 2], [“c”, 1], [“b”, 2], [“a”, 3]] word(“aaaaaaaaaa”) == [[“a”, 10]] word(“”) == [] 这是我的代码: def word(str) words=str.split(“”) count = Hash.new(0) words.map {|char| count[char] +=1 } return count end 我得到了一句话(“aaabbcbbaaa”)=> [[“a”,6],[“b”,4],[“c”,1]],这不是我想要的。 我想计算每个序列。 我更喜欢没有正则表达式的解决方案。 谢谢。

理解可比较的mixin和可枚举的mixin

我是一个新手,学习ruby。 希望能够更好地理解所提出的问题。 我不明白使用类似的mixin和可枚举的mixin。 我的意思是,当我们需要使用它们时,我们不会在课堂中包含这些,对吗? 如果我们想比较两个对象,我们只需写x> y。 那么明确使用它们有什么用?

为什么#each_with_object和#inject会切换块参数的顺序?

#each_with_object和#inject都可用于构建哈希。 例如: matrix = [[‘foo’, ‘bar’], [‘cat’, ‘dog’]] some_hash = matrix.inject({}) do |memo, arr| memo[arr[0]] = arr memo # no implicit conversion of String into Integer (TypeError) if commented out end p some_hash # {“foo”=>[“foo”, “bar”], “cat”=>[“cat”, “dog”]} another_hash = matrix.each_with_object({}) do |arr, memo| memo[arr[0]] = arr end p another_hash # {“foo”=>[“foo”, “bar”], “cat”=>[“cat”, “dog”]} […]

Ruby:在每个之间选择,map,inject,each_with_index和each_with_object

当我多年前开始编写Ruby时,我花了一些时间来理解每个和地图之间的区别。 当我发现所有其他Enumerable和Array方法时,情况会变得更糟。 在官方文档和许多 StackOverflow 问题的帮助下,我慢慢开始了解这些方法的作用。 以下是让我更长时间理解的内容: 我为什么要使用一种方法? 有没有指导方针? 我希望这个问题不是重复的:我对“为什么?”更感兴趣。 比“什么?” 或“如何?”,我认为它可以帮助Ruby新人。