2014-08-28 73 views
0

這是我想要做的,但它不工作。通過數組和提取元素的紅寶石循環

array = [1,2,3,4,5] 

array.each do |val1, val2, val3, val4, val5| 
    puts "#{val1} topic is #{val2}, #{val3} topic is #{val4}, All topics ${val5}" 
end 
+1

在那裏總是5個元素?會有更多?這兩個詞之間的邏輯是什麼? – Anthony 2014-08-28 18:24:16

+1

你想讓你的輸出看起來像什麼? – 2014-08-28 18:24:59

回答

1

array.each將要執行的塊(doend之間的部分)一次每個元素在array中,每次使用該元素作爲塊的第一個參數。

這意味着執行了塊中的第一時間,val1將等於1,和val2val3等將nil因爲只有一個值被傳遞給該塊。第二次執行塊時,val1將等於2val2,val3等每次都會是nil

如果要將數組的元素提取到變量中,則不需要循環。所有你需要做的是這樣的:

val1, val2, val3, val4, val5 = array 
puts "#{val1} topic is #{val2}, #{val3} topic is #{val4}, All topics #{val5}" 

這可能不是必要的,但是,因爲你可以在你的字符串插值引用數組元素直接(#{...}):

puts "#{array[0]} topic is #{array[1]}, #{array[2]} topic is #{array[3]}, All topics #{array[4]}" 
0

如果這是在它們之間的元件和詞語的固定陣列,只是做:

puts "#{array[0]} topic is #{array[1]}, #{array[3]} topic is #{array[4]}, All topics is #{array[5]}" 
0
array = [1,2,3,4,5] 
val1, val2, val3, val4, val5 = array 
puts "#{val1} topic is #{val2}, #{val3} topic is #{val4}, All topics #{val5}" 
2

您可以使用String#%方法:

puts "%d topic is %d, %d topic is %d, All topics $%d" % array 
+2

我是這種方法的粉絲,但你應該包含一個鏈接到['sprintf']的文檔(http://www.ruby-doc.org/core-2.1.2/Kernel.html#method- i-sprintf),因爲它描述了(許多)格式化選項。 – 2014-08-28 18:33:17

+1

你*歡迎*編輯* .. :-) – 2014-08-28 18:35:10

0

這裏的一個方式,其允許的array元素是不同類型的對象,併爲array具有可變長度(以特定的暗示方式定義)。

代碼

def fmt(array) 
    (array[0..-2].each_slice(2) 
       .map { |e| e.join(' topic is ') } \ 
       << "all topics #{array.last}").join(', ') 
end 

實例

fmt [1,2,3,4,5,6,7] 
    #=> "1 topic is 2, 3 topic is 4, 5 topic is 6, all topics 7" 

fmt [2.1,3,"hi","ho",:a] 
    #=> "2.1 topic is 3, hi topic is ho, all topics a" 

array = ["First", "loops", "second", "methods", "third", "metaprogramming", 
     "are important for you to understand"] 

fmt(array) 
    #=> "First topic is loops, second topic is methods, third topic is " + 
    # "metaprogramming, all topics are important for you to understand" 
0

這裏的一個方式,其允許的array元素是不同種類的對象和用於array爲具有可變長度(定義在一種特別的,暗示的方式)。

代碼

def fmt(array) 
    (array[0..-2].each_slice(2) 
       .map { |e| e.join(' topic is ') } 
       .push "all topics #{array.last}") 
       .join(', ') 
end 

實例

fmt([1,2,3,4,5,6,7]) 
    #=> "1 topic is 2, 3 topic is 4, 5 topic is 6, all topics 7" 

fmt([1,2.5,"cat","dog",:symbol]) 
    #=> "1 topic is 2.5, cat topic is dog, all topics symbol" 

array = ["First", "loops", "second", "methods", "third", "metaprogramming", 
     "are important for you to understand"] 

fmt(array) 
    #=> "First topic is loops, second topic is methods, third topic is " + 
    # "metaprogramming, all topics are important for you to understand"