hac13 hac13 - 7 months ago 10
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

'hello'
, 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
end
end
if count > bigcount
bigcount = count
list = (string[0])
string.delete[string[0]]
end
end
return [list,bigcount]
end


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
delete
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

you are using the delete function wrong

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

EDIT

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