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
Related
I am new to Ruby. My past is in Java. I am trying to use a switch case, apparently known as a case expression in Ruby. I want to accept user input, check that input to see if it includes certain characters, and then substitute those characters with other characters. When I try to run this simple program I get many syntax errors but I am not sure why. Could someone please explain to me if I am using this statement wrong and if I can even use case expression in this situation? Thank you.
empty_string = true
while empty_string do
print "Pleathe enter a thtring: "
user_input = gets.chomp
user_input.downcase!
case
when user_input.include? ("s")
user_input.gsub!(/s/, "th")
when user_input.include? ("ch")
user_input.gsub!(/ch/, "th")
when user_input == ""
puts "You typed noting! You get nothing sir!"
when user_input != ""
empty_string = false
else
puts "There are no 's's in your string."
end
end
puts "Zai jian, #{user_input}"
Below are the errors correlating by line and syntax error
rb.rb:9: syntax error, unexpected ( arg, expecting keyword_then or ',' or ';' or '\n'
when user_input.include? ("s")
rb.rb:11: syntax error, unexpected keyword_when, expecting keyword_end
when user_input.include? ("ch")
^
rb.rb:13: syntax error, unexpected keyword_when, expecting keyword_end
when user_input == ""
^
rb.rb:15: syntax error, unexpected keyword_when, expecting keyword_end
when user_input != ""
^
rb.rb:17: syntax error, unexpected keyword_else, expecting keyword_end
rb.rb:21: syntax error, unexpected keyword_end, expecting end-of-input
BELOW IS THE FIXED CODE THANKS TO #Phlip
empty_string = true
while empty_string do
print "Pleathe enter a thtring: "
user_input = gets.chomp
user_input.downcase!
case
when user_input.include?("s")
user_input.gsub!(/s/, "th")
empty_string = false
when user_input.include?("ch")
user_input.gsub!(/ch/, "th")
empty_string = false
when user_input == ""
puts "You typed noting! You get nothing sir!"
empty_string = true
else
puts "There are no 's's in your string."
end
end
puts "Zai jian, #{user_input}"
The issue was the spaces I had after .include?, #Phlip told me Ruby is space sensitive. I removed the white space and it worked. I ran into an issue with the boolean after and fixed that as well. It works as intended now.
My understanding is that you wish to ask the user for a string until the string contains "s" or "ch". When such a string is found you wish to make one or more substitutions in the string and print out a string containing the modified string. Here is a Ruby-like way of doing that.
user_input = nil
loop do
print "Pleathe enter a thtring: "
user_input = "cheater" # gets.chomp.downcase
case user_input
when /s/
user_input.gsub!('s','th')
break
when /ch/
user_input.gsub!('ch','th')
break
when ""
puts "You typed noting! You get nothing sir!"
else
puts "There are no 's's in your string."
end
end
puts "Zai jian, #{user_input}"
If the user enters an empty string, "You typed noting! You get nothing sir!" and then "Pleathe enter a thtring: " are displayed and gets awaits another entry.
If the user enters a non-empty string that contains no "s"'s or "ch"'s, "Pleathe enter a thtring: " is displayed and gets awaits another entry.
If the user enters "Chester\n" "Zai jian, chethter" is diplayed.
If the user enters "Cheater\N" "Zai jian, theater" is displayed.
If you actually wish to replace all "s"'s and "ch"'s, substitute the following for the first two when statements.
when /s|ch/
user_input.gsub!(/s|ch/,'th')
break
If this is done and user enters "Chester" "thethter" is displayed. (The when line could instead be written when /s/, /ch/, but I don't like that as well, in part because /s|ch/ is still needed as gsub!'s first argument.)
Note that case statements use the method Regexp#===. We therefore see that /s/.===(s) #=> true. Ruby allows us to write that /s/ === 'chester' ("syntactic sugar").
user_input = <anything> must precede the loop to make its value visible after the loop.
See Kernel#loop. For other uses of this method the handling of StopIteration exceptions is very useful when working with enumerators (instances of the Enumerator class).
=== looks a lot like ==, but they should be thought of as entirely different methods.
Pretty much have typed code from this example word for word, and receiving following syntax error message. Please help!!
https://github.com/visionmedia/google-search/blob/master/examples/web.rb
My code:
require "rubygems"
require "google-search"
def find_item uri, query
search = Google::Search::Web.new do |search|
search.query = query
search.size = :large
search.each_response {print "."; #stdout.flush}
end
search.find {|item| item.uri =~ uri}
end
def rank_for query
print "%35s " % query
if item = find_item(/vision\-media\.ca/, query)
puts " #%d" % (item.index +1)
else
puts " Not found"
end
end
rank_for "Victoria Web Training"
rank_for "Victoria Web School"
rank_for "Victoria Web Design"
rank_for "Victoria Drupal"
rank_for "Victoria Drupal Development"
Error message:
Ruby Google Search:9: syntax error, unexpected keyword_end, expecting '}'
Ruby Google Search:11: syntax error, unexpected keyword_end, expecting '}'
Ruby Google Search:26: syntax error, unexpected $end, expecting '}'
You've inadvertently commented out the remainder of line 9:
search.each_response {print "."}
Note that the # character in Ruby denotes a comment; i.e., everything on the same line to the right of the # inclusive is considered comment and is not compiled as Ruby code.
print 'this ' + 'is ' + 'compiled'
#=> this is compiled
print 'this' # + 'is' + 'not'
#=> this
Note that the bracket {} notation encapsulates a single executable line contained within a block. What you're trying to do, however, is to execute two commands. For this, it may be more semantically readable to use Ruby's block notation:
search.each_response do
print '.'
STDOUT.flush
end
Instead of #stdout.flush, type $stdout.flush.
The last line of the do block in find_item is:
search.each_response {print "."; #stdout.flush}
Where the # in Ruby marks the beginning of comment. You've commented out the remainder of the line, but not before opening a bracket {. The lack of it being closed is the source of your error.
In order for your code to be correct, you should change the # to $ to access the global stdout object.
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
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
I have the following as part of a class
def to_s
i = 0
first_line? = true
output = ''
#selections.each do | selection |
i += 1
if first_line?
output << selection.to_s(first_line?)
first_line? = false
else
output << selection.to_s
end
if i >= 5
output << "\r"
i = 0
else (output << " $ ")
end
end
return output
end
And i am getting the following syntax errors
SyntaxError: list2sel.rb:45: syntax error, unexpected '='
first_line? = true
^
list2sel.rb:47: syntax error, unexpected keyword_do_block, expecting keyword_end
#selections.each do | selection |
^
list2sel.rb:51: syntax error, unexpected '='
first_line? = false
^
What give, also thanks in advance, this is driving me nuts.
I suppose, you can't name variables with '?' at the end.
Variable names (with a few exceptions noted below) can only contain letters, numbers and the underscore. (Also, they must begin with a letter or the underscore; they can't begin with a number.) You can't use ? or ! in a variable name.
Beyond that rule, there is a strong convention in Ruby that a question mark at the end of something indicates a method that returns a boolean value:
4.nil? # => returns false....
So even if you could use it, a variable like first_line? would confuse (and then annoy) the hell out of Rubyists. They would expect it be a method testing whether something was the first line of something (whatever exactly that means in context).
Exceptions about variable names:
Global variables begin with $ - e.g., $stdin for standard input.
Instance variables begin with # - e.g. #name for an object
Class variables begin with ## - e.g. ##total for a class
I believe this is a more concise way of doing the above (untested):
def to_s
output = ""
#selections.each_with_index do | selection,line |
output << line==0 ? selection.to_s(true) and next : selection.to_s
output << line % 5 ? " $ " : "\r"
end
return output
end
If you are not a fan of the ternary operator (x ? y : z) then you can make them ifs:
def to_s
output = ""
#selections.each_with_index do | selection,line |
if line==0
output << selection.to_s(true)
else
output << selection.to_s
if line % 5
output << " $ "
else
output << "\r"
end
end
end
return output
end
Variable names allow non-ASCII letters, and there are non-ASCII versions of the question mark, so you can put question marks (and also some forms of space characters) into variable names.