从另一个数组填充一个数组
我想创建一个包含每个元素的第一个字母的数组,但我一直只获取整个元素 - 我做错了什么?
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的代码存在几个问题。其中:
first_letter
的数组,但然后在下一行用字符串覆盖它,而不是将字符串添加到其中。 (要将项目添加到数组中,您通常会使用Array#push
或Array#<<
。)first_letter
,这意味着您隐式返回数组本身(假设这就是self
,因为这就是Array#each
返回)。each_group_by_first_letter
时,您向其传递了一个块 (do ...
),但您的方法不接受或使用块。您可能想对each_group_by_first_letter
的结果调用each
。无论如何,Array 类已经拥有您需要的工具——无需为此定义新方法。
There are several problems with your code. Among them:
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 useArray#push
orArray#<<
.)first_letter
, which means you're implicitly returning the array itself (assuming that's whatself
is--because that's whatArray#each
returns).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 calleach
on the result ofeach_group_by_first_letter
.Regardless, the Array class already has the tools you need--no need to define a new method for this.
或者
or