Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

When I tried to shorten an array, I get an error like this:

in `sort_by': undefined method `<=>' for nil:NilClass (NoMethodError)
@@secarr=@@secarr.sort_by{ |hotelname, location, cuisine, price| hotelname }

Please explain because I am a newbie to ruby.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
169 views
Welcome To Ask or Share your Answers For Others

1 Answer

Your code is correct in the respect that hotelname is being compared among the elements in @@secarr. The error message you encountered means that hotelname is (sometimes) nil, and cannot be compared. Comparison can only be done on classes that include Enumerable module. The solution is to, assuming hotelname is normally a string, put to_s after hotelname.

@@secarr = @@secarr.sort_by{|hotelname, location, cuisine, price| hotelname.to_s}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...