Ruby include? in an if-statement - ruby

Why does this result in a syntax error "syntax error, unexpected keyword_end, expecting $end"?:
if "test".include?"te" || "test".include?"fail"
puts "true"
end
The following works:
fail = "test".include?"fail"
if "test".include?"te" || fail
puts "true"
end

Another solution: replace operator "||" with "or" which has lower precedence so you can leave parentheses omitted:
if "test".include?"te" or "test".include?"fail"
puts "true"
end

Use parentheses with those include? arguments.
if "test".include?("te") || "test".include?("fail")
puts "true"
end

You must use a brace around the 2nd parameter.
if "test".include?("te") || "test".include?("fail")
puts "true"
end
or
if "test".include? "te" || ("test".include? "fail" )
puts "true"
end

if "test".include?("te") || "test".include?("fail")
puts "true"
end

Related

How to check if an array includes either X or Y

My assignment is to check whether a given input by the user contains the letters "c" or "s". I managed with one but, I simply don't know the correct way to write that.
I know that the problem is "s" || "c".
print 'What can we do for you?'
user_input = gets.chomp
user_input.downcase!
if user_input.empty?
puts 'Well you will have to write something...!'
elsif user_input.include? 's' || 'c'
puts "We got ourselves some 's's and some 'c's"
user_input.gsub!(/s/, 'th')
user_input.tr!('c', 's')
puts "The Daffy version, #{user_input}!"
else
print "Nope, no 's' or 'c' found"
end
simply
elsif user_input.include?("s") || user_input.include?("c")
or something like
%w(s c).any? { |command| user_input.include? command }
This is the perfect example of where regular expressions are fine:
user_input =~ /[sc]/
or:
(user_input.split('') & %w(s c)).any?
You can use Regexp
user_input[/s|c/]
No regexp:
user_input.count('sc') > 0

ruby if-else one-liner with "puts" not working

I'm trying to do
response = gets.chomp
response == "a" ? puts "yes" : puts "no"
The terminal complains:
syntax error, unexpected ':', expecting keyword_end
response == "a" ? puts "yes" : puts "no"
^
What am I doing wrong?
Here is your error:
response == "a" ? puts "yes" : puts "no"
#=> syntax error, unexpected ':', expecting end-of-input
# response == "a" ? puts "yes" : puts "no"
# ^
Ruby is looking for the first puts' arguments. Since they are not enclosed in parentheses, she assumes they are in a comma-separated list following puts. The first one is "yes", but there is no comma following "yes", so an exception is raised.
Let's try:
response == "a" ? (puts "yes") : puts "no"
#=> syntax error, unexpected tSTRING_BEG, expecting keyword_do or '{' or '('
# response == "a" ? (puts "yes") : puts "no"
# ^
(response == "a" ? puts("yes") : puts "no" raises the same exception.)
I don't know why this doesn't work. The exception says that it is expecting a block (do...end or {..}) or a left parentheses (for enclosing arguments) after the second puts. Kernel#puts calls $stdout.puts. As $stdout returns an IO object, IO#puts is then called, but the doc sheds no light on the problem. Perhaps a reader can offer an explanation.
You could write it as follows:
response == "a" ? (puts "yes") : (puts "no")
or
response == "a" ? puts("yes") : puts("no")
or (best, imo)
puts response == "a" ? "yes" : "no"

Ruby: .grep with regex

I'm using a regular expression to replace all '*' with '[A-Za-z0-9]*' except when the '*' is preceded by '\' like '\*'. How can I ignore the case '\*' ?
code:
puts Regexp.new(val.gsub(/^\*/,'[A-Za-z0-9]*')) =~ str ? 'true' : 'false'
You can use a Negative Lookbehind assertion here.
"foo\\* bar* baz* quz\\*".gsub(/(?<!\\)\*/, '[A-Za-z0-9]*')
# => 'foo\* bar[A-Za-z0-9]* baz[A-Za-z0-9]* quz\*'
You can do this by being more particular in your substitutions:
tests = [
"*.foo",
"\\*.foo"
]
tests.each do |test|
r = test.gsub(/(\\\*|\*)/) do |s|
case ($1)
when "\\*"
$1
else
"[A-Za-z0-9]*"
end
end
puts r
end
Results for me:
[A-Za-z0-9]*.foo
\*.foo
The first capture looks for \* specifically.

How can I logically OR two include? conditions in Ruby?

I am starting learn Ruby, need some help with the include? method.
The below code works just fine:
x = 'ab.c'
if x.include? "."
puts 'hello'
else
puts 'no'
end
But when I code it this way:
x = 'ab.c'
y = 'xyz'
if x.include? "." || y.include? "."
puts 'hello'
else
puts 'no'
end
If gives me error when I run it:
test.rb:3: syntax error, unexpected tSTRING_BEG, expecting keyword_then or ';' o
r '\n'
if x.include? "." || y.include? "."
^
test.rb:5: syntax error, unexpected keyword_else, expecting end-of-input
Is this because the include? method cannot have handle logic operator?
Thanks
The other answer and comment are correct, you just need to include parenthesis around your argument due to Ruby's language parsing rules, e.g.,
if x.include?(".") || y.include?(".")
You could also just structure your conditional like this, which would scale more easily as you add more arrays to search:
if [x, y].any? {|array| array.include? "." }
puts 'hello'
else
puts 'no'
end
See Enumerable#any? for more details.
It's because of Ruby parser, it can't recognize the difference between the passing an arguments and logical operators.
Just modify your code a little bit to distinguish the arguments and operator for Ruby parser.
if x.include?(".") || y.include?(".")
puts 'hello'
else
puts 'no'
end

Case statement character classification

I am trying to classify characters using a case statement, but I am not sure how I would go about this in Ruby.
Here is what I have:
case c
when ('a'..'z'), ('A'..'Z'), '$'
puts "#{c} true"
when ' '
#ignore spaces
else
puts "#{c} false"
end
But this is kind of messy and I'd like to simplify it. Is there anyway to simplify this with a regular expression?
Something like:
case c
when '[a-zA-Z$]'
puts "#{c} true"
when '[\s]'
#ignore whitespace
else
puts "#{c} false"
end
How would something like this be done in Ruby?
Absolutely! But the syntax should be like this:
case c
when /[a-zA-Z$]/
puts "#{c} true"
when /\s/
# ignore
else
puts "#{c} false"
end

Resources