Forum: Ruby on Rails sort_by not working

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
SurviveStyle5 (Guest)
on 2008-12-10 23:34
(Received via mailing list)
I'm having a weird issue where if say....

someobject.items.sort_by {|item| item.key }
#or
someobject.items.sort_by &:key
#then
someobject.items.each do |item|
  #somestuff
end

#somestuff  is not in sorted order. if i use different syntax...

questionnaire.items.sort! { |a,b| a.key <=> b.key }
this works fine. why is that? does it matter?

rails --version
Rails 2.1.1

ruby --version
ruby 1.8.6 (2008-03-03 patchlevel 114) [universal-darwin9.0]


thoughts?
Frederick C. (Guest)
on 2008-12-10 23:51
(Received via mailing list)
On 10 Dec 2008, at 21:33, SurviveStyle5 wrote:

>
> #somestuff  is not in sorted order. if i use different syntax...
>
> questionnaire.items.sort! { |a,b| a.key <=> b.key }
> this works fine. why is that? does it matter?
>

sort_by does not change the array (it returns a new, sorted, array),
as does sort.
sort! on the other hand changes the array you call it on (as the !
indicates)

Fred
SurviveStyle5 (Guest)
on 2008-12-11 00:24
(Received via mailing list)
Thanks! ok i couldn't find sufficient documentation to tell me either
way, thanks! it's always something silly.

On Dec 10, 3:50 pm, Frederick C. <removed_email_address@domain.invalid>
This topic is locked and can not be replied to.