Tuesday, February 9, 2010

Conditional assignment operator in Ruby

Hi, ||= is an operator for assigning value to a variable conditionally in Ruby. See the example below
Here a @secrete is an instance variable contains array of four values. End user guess that values along with the order
If value found and at same position you will see T, If found but not at same position output is 't'. If your guessed value is not at all in the @secrete list your output is F

<%
@secret = %w[chiru ballaya nag venki]

def guess(guess) #where guess is an array of having four values
result = [nil,nil,nil,nil] #array with four nil values
guess.each_with_index do |value, index|
if @secret[index] == value
result[index] = "T"
elsif @secret.include?(value)
result[@secret.index(value)] ||= "t" # ||= is conditional assignment operator, means which will only assign the value if it is currently nil or false. It will not replace if it is already have any value in that variable.
end
end
result.compact.sort.join
end


end
end
guess(%w[chiru nag ballay venki]) #here you are guessing the names and orders.
%>
#output TttT
#Chiru and Venki are exists and also at same positions.
#nag and ballayya are exists but not at same positions.

0 comments: