2

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
3
  • 1
    First of all, you need another end here somewhere. I deduce that you meant it to be before the line x = ["abcd".... Commented Nov 15, 2011 at 4:57
  • yes...i cut down the code to the relevant parts...there is another end in there... Commented Nov 15, 2011 at 5:05
  • Well, your each_group_by_first_letter isn't returning anything explicitly, so in this case it's just returning self. Commented Nov 15, 2011 at 5:11

2 Answers 2

8

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' ]
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.