Reputation: 3390
How do I say if method_one
returns a value, then break, else try 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
Upvotes: 0
Views: 82
Reputation: 15010
You need to use return
. break
is for loops.
def ai_second_move(board)
p "2nd move called"
return if !!method_one(board)
method_two(board)
end
An other fun way would be
def ai_second_move(board)
p "2nd move called"
!!method_one(board) || method_two(board)
end
Upvotes: 0
Reputation: 114218
This would work as well:
method_one(board) and return
The return
statement is executed only if method_one(board)
returns a truthy value.
Upvotes: 0
Reputation: 5774
using if -
method_two(board) if method_one(board).nil?
using unless -
method_two(board) unless !method_one(board).nil?
using ternary -
# 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
Upvotes: 0
Reputation: 6078
Most Ruby way of writing this would be:
method_one(board) || method_two(board)
Ruby executes the right-hand side of ||
only if the left hand side evaluated to false (meaning it returns nil
or false
) and then the result of this expression would be that of the method_two
Upvotes: 7