如果method_one返回值返回值,则在ruby中尝试method_two

时间:2012-10-22 06:53:54

标签: ruby

如何method_one返回值,然后中断,否则请尝试method_two

def ai_second_move(board)
  p "2nd move called"
  # TODO - how to say if method_one gives me a value, break, else method_two
  method_one(board)
  method_two(board) 
end

4 个答案:

答案 0 :(得分:7)

大多数Ruby的写作方式是:

method_one(board) || method_two(board)

只有当左侧评估为false(意味着它返回||nil)时,Ruby才会执行false的右侧,然后此表达式的结果将是method_two

的那个

答案 1 :(得分:0)

您需要使用returnbreak用于循环。

def ai_second_move(board)
  p "2nd move called"
  return if !!method_one(board)

  method_two(board) 
end

另一种有趣的方式是

def ai_second_move(board)
  p "2nd move called"
  !!method_one(board) || method_two(board) 
end

答案 2 :(得分:0)

使用if -

method_two(board) if method_one(board).nil?

使用除非 -

method_two(board) unless !method_one(board).nil?

使用三元 -

# This evaluates if (method_one(board) returns nil) condition. If its true then next statement is method_two(board) else return is executed next.
method_one(board).nil? ? method_two(board) : return

答案 3 :(得分:0)

这也可行:

method_one(board) and return

仅当return返回真值时才会执行method_one(board)语句。