user1043856
user1043856

Reputation: 451

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

Upvotes: 2

Views: 2443

Answers (2)

Jordan Running
Jordan Running

Reputation: 106147

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' ]

Upvotes: 8

Tilo
Tilo

Reputation: 33752

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"] 

Upvotes: 3

Related Questions