Jump to content

The ultimate community for Ruby on Rails developers.


Photo

Can I sort a array containing integers and strings

rails

  • Please log in to reply
1 reply to this topic

#1 roelof

roelof

    Passenger

  • Members
  • 4 posts

Posted 27 May 2014 - 02:58 PM

Hello

 

Let's say I have a array like this [ 1,2,"a"]

 

Is there a way I can sort this.

I tried array.sort but it fails because it can compare fixnum with strings.

 

Roelof

 



#2 Ohm

Ohm

    Driver

  • Moderators
  • 395 posts
  • LocationCopenhagen

Posted 27 May 2014 - 08:39 PM

Depends on how you want it sorted.

["a", 1, 2].sort { |a, b| a.to_s <=> b.to_s } # => [1, 2, "a"]
["a", 1, 2].sort_by(&:to_s) # => [1, 2, "a"]

# This is because "a".to_i == 0
["a", 1, 2].sort_by(&:to_i) # => ["a", 1, 2]

Blog: http://ohm.sh | Twitter: @madsohm





Also tagged with one or more of these keywords: rails

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users