views:

61

answers:

1

I'm trying out to have a block in a while and begin statements in Ruby, but I get a syntax error. Any other way to implement it?

Here's what I want to accomplish

(1..limit).each { |i|
  while (true) do |n|
    x = n * (i%n)
    puts n if n%i != 0
    break if x.even? && !x.zero?
    n += 1
  end
}
+6  A: 

while is a keyword, so you do not need the block. Your code should be:

(1..limit).each { |i|
  while (true)
    x = n * (i%n)
    puts n if n%i != 0
    break if x.even? && !x.zero?
    n += 1
  end
}

But you are requesting a block variable form the while statement. Variable names inside the pipes are for variables passed to your block containing information from whatever calls your block. I will assume that n is supposed to increment. Here is a working version:

(1..limit).each { |i|
  n = 0
  while (true)
    x = n * (i%n)
    puts n if n%i != 0
    break if x.even? && !x.zero?
    n += 1
  end
}

If you really need the code in a block, you could create one and then call it, like this (ruby 1.9 only):

(1..limit).each { |i|
  n = 0
  while (true)
    -> do
      x = n * (i%n)
      puts n if n%i != 0
      break if x.even? && !x.zero?
      n += 1
    end.()
  end
}

By the way, here is a cleaner version:

(1..limit).each do |i|
  n = 0
  loop do
    x = n * (i % n)
    puts n if n % i != 0
    break if x.even? and !x.zero?
    n += 1
  end
end
Adrian
Thanks, I'm using the loop do version more now.