The task:
Write a method that takes in a string. Your method should return the most common letter in the array, and a count of how many times it appears.
Model solution:
def most_common_letter(string) most_common_letter = nil most_common_letter_count = nil idx1 = 0 while idx1 < string.length letter = string[idx1] count = 0 idx2 = 0 while idx2 < string.length if string[idx2] == letter count += 1 end idx2 += 1 end if (most_common_letter_count == nil) || (count > most_common_letter_count) most_common_letter = letter most_common_letter_count = count end idx1 += 1 end return [most_common_letter, most_common_letter_count] end
My solution:
def most_common_letter(string)
most_common_letter = nil
most_common_letter_count = 0
string.delete(" ").each_char do |letter|
letter_count = 0
string.each_char {|test| letter_count+=1 if test == letter }
most_common_letter = letter and most_common_letter_count = letter_count if letter_count > most_common_letter_count
end
[most_common_letter, most_common_letter_count]
end
I tried using more idiomatic Ruby to solve this beginner problem we got in the beginning of the course. I'm wondering about a few things:
- Is using "and" as I did in the if statement idiomatic? I tried a few guesses as to what might work (&&, &, some random characters), but I haven't seen this before.
- I think the delete method alters the original string, and from the wonderful people on this site I've learned that altering the original data is unwise. How else could I ignore the spaces?
- How can I tighten this up?