2013-05-05 234 views
0

while循環我relativly新Ruby或編程好,所以請原諒我,如果我在拍「noob2錯誤與這裏的邏輯。while循環在紅寶石

我試圖使用Chunky_PNG獲取圖像中每個像素的二進制rgba像素值輸出(以及它的位置)

儘管輸出是正確的,但它只顯示第一行,好像外層循環會只能運行一次

是否存在邏輯錯誤,或者while循環中的while循環無法工作? 這樣做可能是不好的做法,我可以想象,但我仍然想知道爲什麼它不是它應該的。

require 'chunky_png' 
image = ChunkyPNG::Image.from_file('test.png') 

#vars 
$width0 = 0 
$widthmax = image.dimension.width.to_i 
$height0 = 0 
$heightmax = image.dimension.height.to_i 

#main 
while $height0 < $heightmax do 
    while $width0 < $widthmax do 
     puts image[$width0,$height0].to_s(2)[0..7] + " " + image[0,0].to_s(2)[8..15] + " " + image[0,0].to_s(2)[16..23] + " " + $height0.to_s + "," + $width0.to_s 
     $width0 += 1 
    end 
    width0 = 0 
    $height0 += 1 
end 
+0

爲什麼你使用全局變量(即帶有'$'前綴的變量)? – 2013-05-05 20:03:48

+0

Globals是教程中使用的第一種類型的血統書我擡頭,所以我想他們是第一選擇 – x3nu 2013-05-05 20:34:19

+3

我建議你找到一個更好的教程。 – 2013-05-05 20:38:10

回答

2

你缺少一個$

你有

width0 = 0 

但是你要

$width0 = 0 

這有永不復位$ width0回零的效果,所以只第一行是輸出。它認爲內部循環不必再次運行,因爲$width0在第一次迭代之後的每次迭代中仍然處於其最大值。

(我也許應該補充一點,全局是不是最好的辦法,正如其他人指出的那樣,但你沒有問爲什麼腳本只輸出第一行的原因。:))

+0

謝謝。 (一個錯字,對我很恥辱......) – x3nu 2013-05-05 20:30:06

0

的錯誤是由雷特里解釋失蹤$符號

即使就越容易使用

each 

的循環。那麼你不需要自己處理循環索引

($height0..$heightmax).each do |height| 
    ($width0..$widthmax).each do |width| 
    puts image[width,height].to_s(2)[0..7] + " " + image[0,0].to_s(2)[8..15] + " " + image[0,0].to_s(2)[16..23] + " " + height.to_s + "," + width.to_s 
    end 
end 
+0

因爲你使用了包含範圍,所以你的每個變體都不相同。因爲我們從0開始索引,所以使用'times'更方便:'heightmax.times {| h | widthmax.times {| w |放圖像[w,h] ...}}' – dbenhur 2013-05-06 00:41:55