Say I have an array of strings that looks like this:
test-3
test-31
test-11
test-12
test-13
test-32
test-10
test-14
I want them sorted like so:
test-3
test-10
test-11
test-12
test-13
test-14
test-31
test-32
arr.sort doesn’t seem to work the way I need. Any help?
Thanks
On Feb 21, 11:54 am, Ed [email protected] wrote:
I want them sorted like so:
Thanks
The sequences of numerals need to be treated as numbers,
not strings.
" test-3
test-31
test-11
test-12
test-13
test-32
test-10
test-14 ".split.sort_by{|s| s[/\d+/].to_i}
==>[“test-3”, “test-10”, “test-11”, “test-12”, “test-13”,
“test-14”, “test-31”, “test-32”]
On 21 Feb 2008, at 17:55, Ed wrote:
I want them sorted like so:
test-3
test-10
test-11
test-12
test-13
test-14
test-31
test-32
arr.sort doesn’t seem to work the way I need. Any help?
It’s sorting lexicographically rather than numerically. Try this
instead:
arr.sort_by { |x| x.split(’-’).last.to_i }
In IRB:
arr = %w( test-3 test-31 test-11 test-12 test-13 test-32 test-10
test-14 )
=> [“test-3”, “test-31”, “test-11”, “test-12”, “test-13”, “test-32”,
“test-10”, “test-14”]
arr.sort
=> [“test-10”, “test-11”, “test-12”, “test-13”, “test-14”, “test-3”,
“test-31”, “test-32”]
arr.sort_by { |x| x.split(’-’).last.to_i }
=> [“test-3”, “test-10”, “test-11”, “test-12”, “test-13”, “test-14”,
“test-31”, “test-32”]
Regards,
Andy S.
On Feb 21, 1:06 pm, William J. [email protected] wrote:
test-32
test-31
test-11
test-12
test-13
test-32
test-10
test-14 ".split.sort_by{|s| s[/\d+/].to_i}
==>[“test-3”, “test-10”, “test-11”, “test-12”, “test-13”,
“test-14”, “test-31”, “test-32”]
Thanks for the response.
arr.split.sort_by{ |s| s[/\d+/].to_i } produces this error message:
“can’t convert Regexp into Integer”
On Feb 21, 1:14 pm, Andrew S. [email protected] wrote:
test-32
test-31
Regards,
Andy S.
-------http://airbladesoftware.com
Works perfectly. Thanks a lot.
On Thu, Feb 21, 2008 at 12:20 PM, Ed [email protected] wrote:
test-12
test-13
" test-3
Thanks for the response.
arr.split.sort_by{ |s| s[/\d+/].to_i } produces this error message:
“can’t convert Regexp into Integer”
William was splitting the string as an example, not an array. Try…
arr.sort_by { |s| s[/\d+/].to_i }
… if you trust your data (i.e. you don’t accidentally have numbers
hanging out elsewhere, like test1-41)
Todd