Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populating an array from another array

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
like image 939
user1043856 Avatar asked Feb 22 '26 23:02

user1043856


1 Answers

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' ]
like image 80
Jordan Running Avatar answered Feb 25 '26 13:02

Jordan Running