views:

28

answers:

1

I'm trying to wrap my head around multithreading, so I'm playing around with Fibers in Ruby. However, when I try to run my script, it tells me I have an unexpected newline character after my ternary statement. Did I miss something about the syntax, here?

timer = Fiber.new do |power|
  power = power.nil? ? 'on' | power 
  start = Time.now 
  loop do 
    if power == 'off'
      now = Time.now
      puts now - start
    end
    power = Fiber.yield
  end
end
+1  A: 

power = power.nil? ? 'on' | power

The proper syntax for this is power = power.nil? ? 'on' : power, with a colon instead of a pipe.

However you could just write this power = 'on' if power.nil?, which is a bit shorter and probably more readable for most people.

Also as a sidenote: is there a paticular reason that you're using 'on' and 'off' instead of true and false?

sepp2k
Thanks, that fixed that right up.Could I rewrite the line that way? I thought it didn't work that way in Fibers because the first call to `Fiber#resume` supplies the argument to the first assignment of the block variable.
Andrew