开发者

Can I have a block in begin/while statement in Ruby?

I'm trying out to have a block in开发者_StackOverflow 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
}


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜