Jakub Ostrowski
Jakub Ostrowski

Reputation: 45

Nil element of array in Ruby

I've got image processing script in Ruby. I want to take all the pixels in an array, and then do the script in which I will change random pixels to make the image noise. But when I getting this pixels I have got a nil error. Here is my code.

require 'mini_magick'
first_image  = MiniMagick::Image.new("123.png")
a = 0
b = 0

pixels = first_image.get_pixels
loop do
  print "\n"
  a=a+1
  while pixels[a][b] != nil do
    print pixels[a][b].to_s + "\n"
    b+=1
  end
  b = 0
  break if pixels[a][b] == nil
end

And this is what I am receiving in a terminal:

Imagenoise.rb:10:in `block in <main>': undefined method `[]' for nil:NilClass (NoMethodError)
    from Imagenoise.rb:7:in `loop'
    from Imagenoise.rb:7:in `<main>'

Upvotes: 0

Views: 65

Answers (2)

spickermann
spickermann

Reputation: 106782

Your code doesn't check if you reached the end of the image. Therefore pixels[a] returns nil at some point (once a is bigger than the number of pixels in the image) and pixel[a][b] fails because you cannot call nil[b].

You can avoid situations like that by not iterating manually through the array and instead use each blocks:

require 'mini_magick'

image  = MiniMagick::Image.new('123.png')
pixels = image.get_pixels

pixels.each do |pixel|
  pixel.each do |color|
    puts color
  end
end

Upvotes: 1

Md. Farhan Memon
Md. Farhan Memon

Reputation: 6121

It is throwing error because pixels[a] is nil and thus pixels[a][b] is in error. You can do something like this to prevent error.

while pixels[a] != nil do
  print pixels[a][b].to_s + "\n"
  b+=1
end

Upvotes: 0

Related Questions