Custom Method not running

Hello,

Why this code is not running, anyone ?

def dictionary_sort arr

return arr if arr.length <=1

middle = arr.pop

less = arr.select{|x| x.downcase < middle.downcase}

more = arr.select{|x| x.downcase >= middle.downcase}

sort(less) + [middle] + sort(more)

end

words = [‘can’,‘feel’,‘singing.’,‘like’,‘A’,‘can’]

puts(dictionary_sort(words).join(’ '))

Error is following:

C:/Users/Nirjhor/RubymineProjects/dictionary sort.rb:20:in
dictionary_sort': undefined methodsort’ for main:Object
(NoMethodError)

            from C:/Users/Nirjhor/RubymineProjects/dictionary 

sort.rb:23:in `<top (required)>’

            from -e:1:in `load'

            from -e:1:in `<main>'

Peace be upon you –

Junayeed Ahnaf N.

Twitter - @Nirjhor http://twitter.com/nirjhor

A method is called upon its receiver object. Your method is defined
such that sort is being called upon implicit receiver ‘self’ (in this
context, self == Object) and passed an argument of either ‘less’ or
‘more’. The Object object doesn’t have a method called ‘sort’, thus
the error message.

To sort object ‘less’ or ‘more’, you need to call sort on those objects:

less.sort + [middle] + more.sort

On Tue, Oct 18, 2011 at 11:44 PM, Junayeed Ahnaf N.

On 10/19/2011 08:44 AM, Junayeed Ahnaf N. wrote:

sort(less) + [middle] + sort(more)

end

words = [‘can’,‘feel’,‘singing.’,‘like’,‘A’,‘can’]

puts(dictionary_sort(words).join(’ '))

Hi,

sort is Array method:

def dictionary_sort arr

return arr if arr.length<=1

middle = arr.pop

less = arr.select{|x| x.downcase< middle.downcase}

more = arr.select{|x| x.downcase>= middle.downcase}

less.sort + [middle] + more.sort

end

Michal

I believe it’s just a typo in the book. If you change sort to
dictionary_sort it runs.

On 10/19/2011 01:44, Junayeed Ahnaf N. wrote:

return arr if arr.length <=1

C:/Users/Nirjhor/RubymineProjects/dictionary sort.rb:20:in dictionary_sort': undefined methodsort’ for main:Object (NoMethodError)

            from C:/Users/Nirjhor/RubymineProjects/dictionary sort.rb:23:in 

`<top (required)>’

            from -e:1:in `load'

            from -e:1:in `<main>'

Take a closer look at the error message. It’s telling you that on line
20 of your source file that you’re attempting to call a method named
“sort” which has not been defined. Maybe there is another method which
you have already defined for sorting arrays that you should use instead.

Sorry to be coy about my answer. However, you appear to be writing your
own sorting method despite the fact that Ruby already includes such a
method for Array objects, so this smells like a homework problem to me.

Good luck! :slight_smile:

-Jeremy

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs