Nifriz
Nifriz

Reputation: 1244

Same procedure doesn't work called in a Thread

I have a problem with Thread in Ruby. It's the first time I use Threads, so maybe I omit something important.

I have this procedure:

  def define_action(field)
    false if field.nil? || field.empty?
    puts field.empty?          <---- ONLY FOR DEBUG
    case field['special']
    when 'signpost'
      typewriter_animation(field['message'])
    else
      typewriter_animation("TO DO ... add action for #{field['special']}") 
    end
  end

typewriter_animation clean a field, puts a text and wait 5 seconds before clear field again.

I use define_action in a Thread

   @timer = Thread.new do
    @engine.define_action(@map.next_field_coordinates)
  end

When field is empty (i see true in prompt) I except nothing as result, but the procedure continue and print on screen "TO DO ... add action for"

The same code without Thread work perfectly, but obviously stop screen for 5 seconds.

What's wrong in my code?

Upvotes: 0

Views: 42

Answers (2)

user28196017
user28196017

Reputation: 11

You must add the return into your code, else the result will be not passed back😌

Upvotes: 1

Kimmo Lehto
Kimmo Lehto

Reputation: 6041

Your guard clause is missing a return.

def define_action(field)
  false if field.nil? || field.empty? # this line does nothing
  ...
end

Should probably be:

def define_action(field)
  return false if field.nil? || field.empty?
  ...
end

I don't see how threads would make any difference.

Upvotes: 3

Related Questions