prompt("Welcome to Calculator! Enter your name:")
name = ''
loop do
name = Kernel.gets().chomp()
if name.empty()?
prompt("Make sure to use a valid name")
else
break
end
end
Not sure what I'm missing here.
I got this error messsage:
syntax error, unexpected keyword_else, expecting ':'
Try out
if name.empty?
Note that you can call methods that have no params without parentheses. Otherwise you should do name.empty?() because ? is part of the name of the method.
Anyway, your mistake is the ? after the if condition. The error message is saying you that with that ? it's trying to process a ternary operator that has this syntax
condition ? expression1 : expression2
for this reason it expects :
Line
if name.empty()?
is interpreted as ternary 'if' operator inside regular if statement:
if (name.empty() ? do_somethig : do_something_else )
and double dot is missing in your code
maybe you meant this:
if name.empty? # is equal to
if name.empty?()
Because question mark is a part of method name
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.
Is the following line proper ruby syntax?
session[:id]?'foo':'bar'
(Notice there is no spacing between the operators)
This line works with all the rubies I tried (>1.8.7) but I understand there can be a misunderstanding as the ? can be part of a method identifier.
Shouldn't it be a syntax error to not put spaces arround the ternary operator?
I believe the correct forms the ternary operator are when selector is the indexed hash, because the char combination ]? is invalid for the same operator:
session[:id]?'foo':'bar'
session[:id] ? 'foo' : 'bar'
session[:id]? 'foo' : 'bar'
But if you omit the space after just the a method and the question mark, this will raise the syntax error:
session?'foo':'bar'
^
SyntaxError: unexpected ':', expecting $end
session? 'foo':'bar'
^
SyntaxError: unexpected ':', expecting $end
If a method identifier has ? as part of it, you would require an additional question mark.
> array_variable.include?('itemA') ? 'yes' : 'no'
>= "yes"
> array_variable.empty? ? 'yes' : 'no'
=> "no"
> array_variable.empty? 'yes' : 'no'
SyntaxError: (irb):10: syntax error, unexpected ':', expecting end-of-input
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.
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
I'm trying to read and process lines from a file in Ruby.
I have a while loop that reads each line. If the all the while loop does is split the lines, it works fine. When I add a regex matching clause, I get a syntax error, unexpected kEND
and syntax error, unexpected $end, expecting kEND
Specifically, here is the code which "compiles"
def validate
invalid = 0
f = File.open(ARGV[0], "r")
while (line = f.gets)
vals = line.split(",")
end
end
if (ARGV[1] == "validate")
validate
end
while this code
def validate
invalid = 0
f = File.open(ARGV[0], "r")
while (line = f.gets)
vals = line.split(",")
match0 = Regexp.new(/0-9]{1,4}/)
unless (match0.match(vals[0]))
invalid ++
end
end
end
if (ARGV[1] == "validate")
validate
end
throws the error
schedule.rb:10: syntax error, unexpected kEND
schedule.rb:18: syntax error, unexpected $end, expecting kEND
The syntax error is not due to the regex. It's due to the "++". Ruby doesn't have the "++" operator. Instead, you should use:
invalid += 1
Besides, there is a bracket missing in your regexp (character class).
/0-9]{1,4}/
It should read
/[0-9]{1,4}/
There is no C-style increment/decrement operator. Instead use
invalid = invalid + 1
or
invalid += 1