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
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 use Array#push or Array#<<.)first_letter, which means you're implicitly returning the array itself (assuming that's what self is--because that's what Array#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 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' ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With