hac13 hac13 - 2 years ago 83
Ruby Question

Why does `String#delete` return an error in my ruby code?

The goal is to take a string and return the most common letter along with it's count. For string

, it would return
['l', 2]

I've written the following:

def most_common_letter(string)
list = []
bigcount = 0
while 0 < string.length
count = 0
for i in 0..string.length
if string[0] == string[i]
count += 1
if count > bigcount
bigcount = count
list = (string[0])
return [list,bigcount]

I get the following error:

wrong number of arguments (0 for 1+)
(repl):14:in `delete'
(repl):14:in `most_common_letter'
(repl):5:in `initialize'

Please help me understand what I'm doing wrong with the
statement, or what else is causing this to return an error.

I have a solution done another way, but I thought this would work just fine.

Answer Source

you are using the delete function wrong

Use string.delete(string[0]) instead of string.delete[string[0]]


As for the infinite loop you mentioned. Your condition for while is 0 < string.length

And you expect the string.delete[string[0]] statement to actually delete a character at a time.

But what exactly it does is, it deletes a character and returns the new string, but it never actually mutates/changes the actual string.

So try changing it to string = string.delete[string[0]]

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download