从另一个数组填充一个数组

发布于 2024-12-15 16:54:30 字数 313 浏览 2 评论 0 原文

我想创建一个包含每个元素的第一个字母的数组,但我一直只获取整个元素 - 我做错了什么?

def each_group_by_first_letter
  self.each do |x| 
    first_letter = []
    first_letter = x[0, 1].to_s
  end

  x = ["abcd", "efgh", "able"]
  x.each_group_by_first_letter do |letter, words|
    printf("%s: %s\n", letter, words)
  end

I would like to create an array with the first letter from each element, but I keep just getting the entire element - what am I doing wrong?

def each_group_by_first_letter
  self.each do |x| 
    first_letter = []
    first_letter = x[0, 1].to_s
  end

  x = ["abcd", "efgh", "able"]
  x.each_group_by_first_letter do |letter, words|
    printf("%s: %s\n", letter, words)
  end

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

青萝楚歌 2024-12-22 16:54:30

您的代码存在几个问题。其中:

  • 您创建一个名为 first_letter 的数组,但然后在下一行用字符串覆盖它,而不是将字符串添加到其中。 (要将项目添加到数组中,您通常会使用 Array#pushArray#<<。)
  • 您不返回 first_letter,这意味着您隐式返回数组本身(假设这就是 self ,因为这就是 Array#each 返回)。
  • 当您调用 each_group_by_first_letter 时,您向其传递了一个块 (do ...),但您的方法不接受或使用块。您可能想对 each_group_by_first_letter 的结果调用 each

无论如何,Array 类已经拥有您需要的工具——无需为此定义新方法。

x = [ 'abcd', 'efgh', 'able' ]

x.map {|word| word[0] }
# => [ 'a', 'e', 'a' ]

There are several problems with your code. Among them:

  • You create an array called first_letter, but then overwrite it with a string on the next line instead of adding the string to it. (To add an item to an array you will usually use Array#push or Array#<<.)
  • You don't return first_letter, which means you're implicitly returning the array itself (assuming that's what self is--because that's what Array#each returns).
  • When you call each_group_by_first_letter you pass it a block (do ...) but your method doesn't take or use a block. You probably mean to call each on the result of each_group_by_first_letter.

Regardless, the Array class already has the tools you need--no need to define a new method for this.

x = [ 'abcd', 'efgh', 'able' ]

x.map {|word| word[0] }
# => [ 'a', 'e', 'a' ]
长梦不多时 2024-12-22 16:54:30
x = ["abcd", "efgh", "able"]
y = x.map{|e| e[0]}          # keeps x intact

或者

x = ["abcd", "efgh", "able"]
x.map!{|e| e[0]}             # modifies x

 => ["a", "e", "a"] 
x = ["abcd", "efgh", "able"]
y = x.map{|e| e[0]}          # keeps x intact

or

x = ["abcd", "efgh", "able"]
x.map!{|e| e[0]}             # modifies x

 => ["a", "e", "a"] 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文