如何在Ruby中对输入进行大写和排序?

时间:2015-10-02 17:13:59

标签: ruby

我的代码需要我输入的5个单词始终按字母顺序排列,我不知道该怎么做。

我已经完成了大写和小写,但我也需要它来同时对我输入的单词进行排序。

这是我到目前为止所做的:

tasks = []
5.times do 
  puts "Please enter a word:"
  tasks << gets.chomp
end

puts "Here are your words:" 

tasks.each_with_index do |team, index|
  if index.even?
    puts team.upcase
  else
    puts team.downcase
  end
end

3 个答案:

答案 0 :(得分:2)

更改

tasks.each_with_index

tasks.sort.each_with_index

<小时/> 更好地重写整个代码:

tasks = Array.new(5) do 
  puts "Please enter a word:"
  gets.chomp
end
puts "Here are your words:" 
tasks.sort.each_slice(2) do |even, odd|
  puts even.upcase, *(odd.downcase if odd)
end

答案 1 :(得分:1)

假设您希望排序不区分大小写并希望在条目排序后进行大写/小写,您可以这样做:

["CAT", "hat", "IN", "the", "THE"]

如果条目为&#34;&#34;,&#34; cat&#34;,&#34;和&#34;,&#34;&#34;,&#34; hat&#34 ;,这将返回:

angular.module('myApp')
    .config(['$routeProvider', function($routeProvider) {
        $routeProvider.when('/home', {
            templateUrl: '/path/to/template',
            controller: 'myCtrl',
            controllerAs: 'ctrl',
            resolve: {
                myData: ['$http', function($http) {
                    return $http.get('/end/point');
                }
            }
        }
    }]);

答案 2 :(得分:0)

只需在数组上调用sort

tasks.sort.each_with_index do |team, index|
  # ...

我建议在文档中阅读关于数组和其他核心类的所有其他有用方法。