ruby - 根据每个嵌套数组的第一个元素对 Ruby 数组重新排序

标签 ruby arrays hash multidimensional-array

我的目标是将 a 转换为 b:

a = [["a","b"], ["d", "c"], ["a", "o"], ["d", "g"], ["c", "a"]]
b = [[["a","b"], ["a", "o"]], ["c", "a"], [["d", "c"], ["d", "g"]]

它们按每个嵌套数组中的第一个元素分组。到目前为止,我有:

def letter_frequency(c)
  d = Hash.new(0)
  c.each do |v|
    d[v] += 1
  end
  d.each do |k, v|
  end
  end

def separate_arrays(arry)
  arry2 = []
  arry3 = []
  big_arry = []
  y = 0
 while y < arry.length 
    arry2.push(arry[y][0])
    arry3.push(arry[y][1])         
    y += 1
 end
  freq = letter_frequency(arry2)
  front = arry.slice!(0..(freq["a"] - 1))
end

separate_arrays(a)

这不仅看起来有点矫枉过正,而且现在可以保证“a”将是合法的哈希键,所以最后一部分不起作用。感谢您的帮助。

最佳答案

你可以尝试做这样的事情:

a.group_by(&:first).values.map {|e| e.length > 1 ? e : e.flatten}
# => [[["a", "b"], ["a", "o"]], [["d", "c"], ["d", "g"]], ["c", "a"]]

我使用以下方法:

Enumerable#group_by (按数组的第一个元素,如您的问题):

Returns a hash, which keys are evaluated result from the block, and values are arrays of elements in enum corresponding to the key.

Hash#values :

Returns a new array populated with the values from hsh. See also Hash#keys.

Enumerable#map (必需,因为当只有一个匹配项时您不想获得嵌套数组,例如 c 字母):

Returns a new array with the results of running block once for every element in enum.

Enumerable#flatten :

Returns a new array that is a one-dimensional flattening of this array (recursively). That is, for every element that is an array, extract its elements into the new array. If the optional level argument determines the level of recursion to flatten

关于ruby - 根据每个嵌套数组的第一个元素对 Ruby 数组重新排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9564657/

相关文章:

c# - F# 是否具有与 C#'s "unsafe"block 等效的语法

sorting - Groovy:按值对哈希键进行排序

java - 从字符串生成唯一的整数 ID

sql - 这是什么样的密码哈希/加密?

ruby-on-rails - 直接引用模型和在类方法中使用self有什么区别?

ruby-on-rails - 为多个 Rails 对象呈现 JSON

ruby-on-rails - Rails 7 - has_many_attached 加载新附件时删除旧附件

ruby - Ruby 新手,遇到 LOAD_PATH 问题

php - 如何从数组中删除值但保持索引不变

arrays - 通过 Graph API 将照片发布到 Facebook : OAuthException: (#100) param tags must be an array