# Sort\_by \['-100', 'dog', '-1000','cat'\]?

**URL:** <https://www.ruby-forum.com/t/sort-by-100-dog-1000-cat/260562>\
**Category:** Uncategorized\
**Created:** [December 5, 2020, 8:19pm UTC](https://www.ruby-forum.com/t/sort-by-100-dog-1000-cat/260562 "2020-12-05T20:19:13Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![brater](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/a88e4f/32.png) [@brater](https://www.ruby-forum.com/u/brater)\
**Post date:** [December 5, 2020, 8:19pm UTC](https://www.ruby-forum.com/t/sort-by-100-dog-1000-cat/260562/1 "2020-12-05T20:19:14Z")

</div>

trying to solve this puzzle, but I do not know how.

given some array of strings with numbers and words , how to sort it, so I could put in a given order by digit and word length?  
Thanks.

---

<div class="post-metadata">

**Author:** ![SouravGoswami](https://www.ruby-forum.com/user_avatar/www.ruby-forum.com/souravgoswami/32/2543_2.png) [@SouravGoswami](https://www.ruby-forum.com/u/SouravGoswami)\
**Post date:** [December 5, 2020, 10:05pm UTC](https://www.ruby-forum.com/t/sort-by-100-dog-1000-cat/260562/2 "2020-12-05T22:05:55Z")

</div>

To sort an array items by their word length alone, you would do:

```auto
['-100', 'dog', '-1000', 'cat'].sort_by { |x| x.length } # => ["dog", "cat", "-100", "-1000"]

# Or #

['-100', 'dog', '-1000', 'cat'].sort_by(&:length) # => ["dog", "cat", "-100", "-1000"]

```

To sort them by character alone, you can do this:

```auto
['-100', 'dog', '-1000', 'cat'].sort # => ["-100", "-1000", "cat", "dog"]

```

To sort them by digit first:

```auto
['-100', 'dog', '-1000', '10', 'cat'].sort_by { |x|
	x.to_i.to_s == x ? -1 : 1
} # => ["-100", "-1000", "10", "dog", "cat"]

```

To sort them with digit and length combined, where digits comes first and then the strings:

```auto
['-100', 'dog', '-1000', '10', 'cat', 'capybara', 'mouse'].sort_by { |x|
	x.to_i.to_s == x ? -1 : x.length
} # => ["-100", "-1000", "10", "dog", "cat", "mouse", "capybara"]

```

To sort them with the length of the digits where digits come first and then sort them the length of strings:

```auto
['-100', 'dog', '1000000', '-1000', '10', 'cat', 'capybara', 'mouse'].sort_by { |x|
	x.to_i.to_s == x ? -x.length : x.length
} # => ["1000000", "-1000", "-100", "10", "dog", "cat", "mouse", "capybara"]

```

To sort the array with integers, and then sort with characters:

```auto
['-100', 'dog', '1000000', '-1000', '10', 'cat', 'capybara', 'mouse'].partition { |x|
	x.to_i.to_s == x
}.each(&:sort!).flatten # => ["-100", "-1000", "10", "1000000", "capybara", "cat", "dog", "mouse"]

```
