2011-10-12 38 views
0

我試圖創建一個程序,用戶可以輸入多個名稱。然後這些名稱按字母順序依次顯示,並向後打印(顯示)每個第二個名稱。我已經通過了幾個教程,這是我第二天使用紅寶石..這是我到目前爲止。使用多個變量對數組進行排序

name_list = {} 
puts 'please enter names seperated by a space:' 
name_list = gets.chomp 
names = name_list.split(" ") 

搶名字......

names.sort do |a,b| a.upcase <=> b.upcase end 
display = "#{names}" 
for ss in 0...display.length 
     print ss, ": ", display[ss], "\n" 
end 

,按字母順序,並在相互排列。 我真的很努力地將它們結合在一起我認爲我在這裏至少有半打錯誤...如果我在錯誤的道路上有人可以指導我一些信息,所以我可以重新開始?

編輯

我也有過這樣的想法使用的一類。 但我將不得不編程的名字,我希望用戶能夠通過CONSOL添加信息。 A類

DEF初始化(名稱) @name =名 端 DEF to_s @ name.reverse 端 端

>> a = [A.new("greg"),A.new("pete"),A.new("paul")] 

>> puts a 
+0

什麼是你想實現與最後一個循環?什麼是預期的輸出? – Wukerplank

回答

1
puts 'please enter names seperated by a space`enter code here` :' 
names = gets.chomp.split(" ") 

names.sort! {|a,b| a.upcase <=> b.upcase } # For a single line use {..} instead of do..end 

names.each_with_index do |n,i| 
    if i % 2 == 0 
    p n 
    else 
    p n.reverse 
    end 
end 

您也可以用在二進制運算符,在這種情況下,我使用了完整的if else塊來提高可讀性。

names.each_with_index do |n,i| 
    p (i % 2 == 0) ? n : n.reverse 
end 

編輯

command = "" 
names = [] 
while command != "exit" 
    puts 'please enter names seperated by a space`enter code here` :' 

    command = gets.chomp! 

    if command == "display" 
    names.sort! {|a,b| a.upcase <=> b.upcase } # For a single line use {..} instead of do..end   
    names.each_with_index do |n,i| 
     if i % 2 == 0 
     p n 
     else 
     p n.reverse 
     end 
    end 
    else 
    names << command 
    end 
end 
+0

我通常會避免使用三元運算符,因爲它會損害代碼的可讀性。然而,在這種情況下,使用它是一個好的情況。另外,OP以不區分大小寫的方式排序,你應該這樣做。 – Romain

+0

感謝的人..會有可能加入觸發器說他可以輸入儘可能多的名字,但是當他鍵入「display」時,例如,然後它會顯示名稱..通過你搖動我的襪子的方式。我用我的谷歌福,並無法獲得任何:) –

+0

@Romain,很好的發現。我改變了這一點。 – Gazler

2

那麼幾個要點:

names.sort do |a,b| a.upcase <=> b.upcase end # Will not modify the "names" array, but will return a sorted array. 
names.sort! do |a,b| a.upcase <=> b.upcase end # Will modify the "names" array. 

要顯示你的名字:在你的代碼

names.each_with_index do |name, index| 
    if index % 2 == 0 
     puts name 
    else 
     puts name.reverse 
    end 
end 
+0

因此,如果我想打印他們在eachother下,我會在結尾處添加/ n或打印名稱? –

+0

@Sliknox或使用'puts'而不是'print',因爲我在編輯中。 – Romain

+0

非常感謝你的伴侶! merci bouque !! –

3

問題:

  • name_list在頂部定義爲空散列但未使用。
  • split(「」) - >分割
  • sort {| a,b | a.method < => b.method} - > sort_by {| x | x.method} - > sort_by(&:方法)
  • 排序不是就地操作,請指定結果(或直接使用它)。
  • display =「#{names}」 - > display = names
  • for ss in 0 ... display.length - > enumerable.each_with_index {| item,index | ...}
  • 不要寫do/end單行,使用{...}

我會寫:

puts 'Please enter names separated by spaces' 
gets.split.sort_by(&:upcase).each_with_index do |name, index| 
    puts "%s: %s" % [index, (index % 2).zero? ? name : name.reverse] 
end 
+0

謝謝我,我以爲我有一些問題!是的...我剛剛在昨天開始使用紅寶石。語法如此簡單令人困惑。我習慣了很多統一的程序...你搖晃我的襪子.. –