Sort an array alphabetically in Ruby but with capitalised words at the end
2015-04-30 09:07
836 查看
1、["Apple", "banana", "Zebra", "orange"].sort_by(&:swapcase)
Probably
not a concern, but ["iPhone",
"item"].sort_by(&:swapcase) #=> ["item", "iPhone"]
,["IRB", "It"].sort_by(&:swapcase) #=> ["It", "IRB"]
2、Yet another way:
arr = %w{ Apple banana Zebra Camel iPhone waffles Pancakes } # => ["Apple", "banana", "Zebra", "Camel", "iPhone", "waffles", "Pancakes"] arr.sort.rotate(arr.count { |s| s[/^[A-Z]/] }) # => ["banana", "iPhone", "waffles", "Apple", "Camel", "Pancakes", "Zebra"]
We have:
a = arr.sort # => ["Apple", "Camel", "Pancakes", "Zebra", "banana", "iPhone", "waffles"] nbr_capitalized_words = arr.count { |s| s[/^[A-Z]/] } #=> 4 a.rotate(nbr_capitalized_words) #=> ["banana", "iPhone", "waffles", "Apple", "Camel", "Pancakes", "Zebra"]
3、["banana", "Banana","orange", "Apple", ].sort_by{|x| [x[0].upcase==x[0] ? 1:0,x] }
相关文章推荐
- How do I sort an array of hashes by a value in the hash?
- Data Structure Array: Find the two numbers with odd occurrences in an unsorted array
- How do I sort an array of hashes by a value in the hash?
- An asset is marked with HideFlags.DontSave but is included in the build
- Whats the best way to split an array in ruby into multiple smaller arrays of random size
- 打包的时候报错 An asset is marked with HideFlags.DontSave but is included in the build的解决办法
- How to sort an NSMutableArray with custom objects in it?
- An asset is marked with HideFlags.DontSave but is included in the build 解决方法
- How to sort an array in Ruby to a particular order?
- The filename 未命名.ipa in the package contains an invalid character(s). The valid characters are: A-Z, a-z, 0-9, dash, period, underscore, but the name cannot start with a dash, period, or underscore
- Sort an Array Mixed With Integers and Strings - Ruby
- 错误:Mixed Content: The page at ‘https://XXX’ was loaded over HTTPS, but requested an insecure........
- An asset is marked with HideFlags.DontSave but is included in the build:
- Unity 解决 An asset is marked with HideFlags.DontSave but is included in the build 问题。
- Unity5 使用自带的字体导致BuildAssetbundle失败An asset is marked with HideFlags.DontSave but is included in the
- Ruby: Sorting an array of strings, in alphabetical order, that includes some arrays of strings
- react Warning: Each child in an array or iterator should have a unique "key" prop. Check the render
- You called this URL via POST, but the URL doesn't end in a slash and you hav。。。
- An instance of getting the maximum and minimum values in an array
- SDK location not found. Define location with sdk.dir in the local.properties file or with an ANDROID