ruby boolean operator or || difference [duplicate] - ruby

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Ruby: difference between || and 'or'
In ruby, isn't 'or' and '||' the same thing? I get different results when I execute the code.
line =""
if (line.start_with? "[" || line.strip.empty?)
puts "yes"
end
line =""
if (line.start_with? "[" or line.strip.empty?)
puts "yes"
end

No, the two operators have the same effect but different precedence.
The || operator has very high precedence, so it binds very tightly to the previous value. The or operator has very low precedence, so it binds less tightly than the other operator.
The reason for having two versions is exactly that one has high precedence and the other has low precedence, since that is convenient.

In the first case you used || wich is evaluated prior than anything else in the statement due to the precedence well stated by other answeres, making it clearer with some parenthesis added, your first statement is like:
(line.start_with? ("[" || line.strip.empty?))
wich translates to
(line.start_with? ("["))
resulting FALSE
In the other hand, your second statement translates to
((line.start_with? "[") or line.strip.empty?)
wich translates to
(FALSE or TRUE)
resulting true
That´s why I try to use parenthesis everytime I call a function. :-)

Daniel is right, more clearly:
if (line.start_with?("[") || line.strip.empty?)
puts "yes"
end
will produce yes

Related

Rubocop rule so that multiline conditional assignments start the condition on the next line

In rubocop, I'd like to enforce that multiline conditional assignments indent all lines within the conditional from the beginning of the line instead of after the assignment operator. It should force the conditional to the next line. Did a bunch of searching / experimentation but couldn't find a solution. Best configuration I found was:
Layout/EndAlignment:
EnforcedStyleAlignWith: "keyword"
Layout/MultilineAssignmentLayout:
EnforcedStyle: "new_line"
Those rules allow both of the following; would like to exclude and ideally autocorrect the first into the second.
# bad
mode = if keys.count == 0
'Solo'
else
'Multi'
end
# good
mode =
if keys.count == 0
'Solo'
else
'Multi'
end
Not interested in using the ternary operator since this needs to support large conditional blocks.

Case Statement using || (OR)

The following code I am trying to use to assign an email alias via an api to our ticketing system.
#email.cc_list = case #site_id
when /site1/ || /site2/; "smail-alias-1"
when /site3/ || /site4/ || /site5/ || /site6/; "email-alias-2"
when /site7/ || /site8/; "email-alias-3"
when /site9/; "email-alias-4"
when /site10/; "email-alias-5"
end
the problem is that only site 1, 3, 7, 9, and 10 are actually being assigned properly. anything after the || isn't working.
I would rather avoid 10 when statements for 5 alias's. Is there a way that I can make this case statement work with a hash in order to get the system to determine when it matches the specified site_id? or another way to make the or functions work?
You could write :
#email.cc_list = case #site_id
when /site(1|2)/ then "smail-alias-1"
when /site(3|4|5|6)/ then "email-alias-2"
when /site(7|8)/ then "email-alias-3"
when /site9/ then "email-alias-4"
when /site10/ then "email-alias-5"
end
Not to give you the correct ways since others have done that, but will be good for your knowledge why your original code fails.
case #site_id
when /site1/ || /site2/ ...
does not translate to:
if #site_id =~ /site1/ || #site_id =~ /site2/ ...
but to:
if #site_id =~ /site1/ || /site2/ ...
which is parsed as:
if ((#site_id =~ /site1/) || /site2/) ...
so, when the first match fails, it returns nil. nil ||-ed with a regex object has the value of regex object itself. A regex object in condition has boolean value of... you guess: false
you will even get a:
warning: regex literal in condition
if you do it directly in an if statement.
You might prefer to write:
#email.cc_list = case #site_id[/\d+/].to_i
when 1,2 then "smail-alias-1"
when 3..6 then "email-alias-2"
when 7,8 then "email-alias-3"
when 9 then "email-alias-4"
when 10 then "email-alias-5"
end
You could join your regexes w/ Regexp.union:
#email.cc_list = case #site_id
when Regexp.union(/site1/, /site2/); "smail-alias-1"
when Regexp.union(/site3/, /site4/, /site5/, /site6/); "email-alias-2"
when Regexp.union(/site7/, /site8/); "email-alias-3"
when /site9/; "email-alias-4"
when /site10/; "email-alias-5"
end
Or make the regex like /site1|site2/ yourself which is what union would basically do for you here.

If statement not working - what is wrong with this syntax?

I get an "Expected Identifier" message against the if line. Any ideas why?
if ([inputA.text isEqualToString:#""]) && ([inputB.text <> isEqualToString:#""]) {
c = 1;
}
I'm trying to say it both inputs are empty...
I presume there isn't an easier way to say if the text is null in Obj C++?
An if statement requires that its condition expression be enclosed in parentheses. You have a compound expression. You've used parentheses around the subexpressions of the logical AND operation (&&), but you haven't surrounded the entire expression in parentheses. (The subexpressions don't actually require parentheses in this case, but they don't hurt.)
Next, you have a random <> in the second subexpression. What is that doing in there? In some languages that is the "not equal" operator, but a) it's not an operator in C or Objective-C, b) it wouldn't go inside a message-send expression like that, and c) you claim you were trying to check that both inputs are empty, so I wouldn't expect you to try to negate the test for equality with the empty string.
So, fixing just those problems yields:
if ([inputA.text isEqualToString:#""] && [inputB.text isEqualToString:#""]) {
c = 1;
}
That said, pie's answer is good, too. It also works if either of the inputs has a nil text property, too.
if ([inputA.text length]==0 && [inputB.text length]==0)
{
c = 1;
}

Converting a string to a condition in Ruby

I actually have a string called "cond". This is the content of that string:
"20 < 50"
I would like to insert it into a condition like this: (example)
if 20 < 50
return "Hello"
But that condition is a string, so I can't write this:
if cond
return "Hello"
So I would like to know if it is possible to convert a string to a condition to set in an "if" condition. And if it is possible, how can I do it ?
Thank you.
eval might just be your friend here:
>> eval('20 < 50')
=> true
However, eval will execute the arbitrary code inside its argument; you should be sure that your cond can't contain anything detrimental to your system's health!
One alternative to using eval is perhaps to write an evaluator (or use/modify an existing one, like this one by Sterling Camden).
As is his code requires you to write lt, gt, eq, and so on, instead of <, >, ==, ... . As noted in a comment in calc.rb:
# Equality and its clan (note we cannot use '==' or other two-character
# non-word operators, because of the way we parse the string. Non-word
# characters come in one at a time.
If you know the condition will always be basic like the example you provided, you can do this:
left, op, right = "20 < 50".split
cond = left.to_i.send(op.to_sym, right.to_i)

Checking if a string has balanced parentheses

I am currently working on a Ruby Problem quiz but I'm not sure if my solution is right. After running the check, it shows that the compilation was successful but i'm just worried it is not the right answer.
The problem:
A string S consisting only of characters '(' and ')' is called properly nested if:
S is empty,
S has the form "(U)" where
U is a properly nested string,
S has
the form "VW" where V and W are
properly nested strings.
For example, "(()(())())" is properly nested and "())" isn't.
Write a function
def nesting(s)
that given a string S returns 1 if S
is properly nested and 0 otherwise.
Assume that the length of S does not
exceed 1,000,000. Assume that S
consists only of characters '(' and
')'.
For example, given S = "(()(())())"
the function should return 1 and given
S = "())" the function should return
0, as explained above.
Solution:
def nesting ( s )
# write your code here
if s == '(()(())())' && s.length <= 1000000
return 1
elsif s == ' ' && s.length <= 1000000
return 1
elsif
s == '())'
return 0
end
end
Here are descriptions of two algorithms that should accomplish the goal. I'll leave it as an exercise to the reader to turn them into code (unless you explicitly ask for a code solution):
Start with a variable set to 0 and loop through each character in the string: when you see a '(', add one to the variable; when you see a ')', subtract one from the variable. If the variable ever goes negative, you have seen too many ')' and can return 0 immediately. If you finish looping through the characters and the variable is not exactly 0, then you had too many '(' and should return 0.
Remove every occurrence of '()' in the string (replace with ''). Keep doing this until you find that nothing has been replaced (check the return value of gsub!). If the string is empty, the parentheses were matched. If the string is not empty, it was mismatched.
You're not supposed to just enumerate the given examples. You're supposed to solve the problem generally. You're also not supposed to check that the length is below 1000000, you're allowed to assume that.
The most straight forward solution to this problem is to iterate through the string and keep track of how many parentheses are open right now. If you ever see a closing parenthesis when no parentheses are currently open, the string is not well-balanced. If any parentheses are still open when you reach the end, the string is not well-balanced. Otherwise it is.
Alternatively you could also turn the specification directly into a regex pattern using the recursive regex feature of ruby 1.9 if you were so inclined.
My algorithm would use stacks for this purpose. Stacks are meant for solving such problems
Algorithm
Define a hash which holds the list of balanced brackets for
instance {"(" => ")", "{" => "}", and so on...}
Declare a stack (in our case, array) i.e. brackets = []
Loop through the string using each_char and compare each character with keys of the hash and push it to the brackets
Within the same loop compare it with the values of the hash and pop the character from brackets
In the end, if the brackets stack is empty, the brackets are balanced.
def brackets_balanced?(string)
return false if string.length < 2
brackets_hash = {"(" => ")", "{" => "}", "[" => "]"}
brackets = []
string.each_char do |x|
brackets.push(x) if brackets_hash.keys.include?(x)
brackets.pop if brackets_hash.values.include?(x)
end
return brackets.empty?
end
You can solve this problem theoretically. By using a grammar like this:
S ← LSR | LR
L ← (
R ← )
The grammar should be easily solvable by recursive algorithm.
That would be the most elegant solution. Otherwise as already mentioned here count the open parentheses.
Here's a neat way to do it using inject:
class String
def valid_parentheses?
valid = true
self.gsub(/[^\(\)]/, '').split('').inject(0) do |counter, parenthesis|
counter += (parenthesis == '(' ? 1 : -1)
valid = false if counter < 0
counter
end.zero? && valid
end
end
> "(a+b)".valid_parentheses? # => true
> "(a+b)(".valid_parentheses? # => false
> "(a+b))".valid_parentheses? # => false
> "(a+b))(".valid_parentheses? # => false
You're right to be worried; I think you've got the very wrong end of the stick, and you're solving the problem too literally (the info that the string doesn't exceed 1,000,000 characters is just to stop people worrying about how slow their code would run if the length was 100times that, and the examples are just that - examples - not the definitive list of strings you can expect to receive)
I'm not going to do your homework for you (by writing the code), but will give you a pointer to a solution that occurs to me:
The string is correctly nested if every left bracket has a right-bracket to the right of it, or a correctly nested set of brackets between them. So how about a recursive function, or a loop, that removes the string matches "()". When you run out of matches, what are you left with? Nothing? That was a properly nested string then. Something else (like ')' or ')(', etc) would mean it was not correctly nested in the first place.
Define method:
def check_nesting str
pattern = /\(\)/
while str =~ pattern do
str = str.gsub pattern, ''
end
str.length == 0
end
And test it:
>ruby nest.rb (()(())())
true
>ruby nest.rb (()
false
>ruby nest.rb ((((()))))
true
>ruby nest.rb (()
false
>ruby nest.rb (()(((())))())
true
>ruby nest.rb (()(((())))()
false
Your solution only returns the correct answer for the strings "(()(())())" and "())". You surely need a solution that works for any string!
As a start, how about counting the number of occurrences of ( and ), and seeing if they are equal?

Resources