What is wrong with my Ruby case statement syntax? [duplicate] - ruby

This question already has answers here:
No increment operator (++) in Ruby? [duplicate]
(3 answers)
Closed 1 year ago.
I am trying to sift digits from a numeral string and count each occurrence of each different numeral.
To my eyes, my syntax looks correct but I am constantly receiving a syntax error on my case statement; "unexpected 'when'".
Can someone please tell me what I am doing wrong here?
prime_string = "23571113171923293137414347535961677173798389971011031071091131271311371391"
zeroes = 0
ones = 0
twos = 0
count_array = [zeroes, ones, twos]
def numsort(d)
case d
when 0
zeroes++
when 1
ones++
when 2
twos++
else
puts "err"
end
end
while prime_string.length > 0 do
numsort(prime_string.split.shift)
end
puts count_array

There is no ++ operator in ruby.
You need to write += 1 instead.
Whilst this would admittedly have caused a somewhat cryptic error message due to the syntax error, a couple of things I'd note are:
Read the error message carefully. It tells you the line number of the error which, in this case, should probably point to the first occurrence of ++?
Use a better IDE/editor setup! Coding in a poor environment is like writing software whilst wearing handcuffs. Your editor should have warned you about invalid syntax here, before even trying to run the code.

Related

I am having trouble with my ruby game please [duplicate]

This question already has answers here:
Dynamic constant assignment
(7 answers)
Closed 2 years ago.
I am trying to make a game for ruby but I keep getting the following error at PlayerMove = $STDIN.gets.chomp:
dynamic constant assignment error
I tried changing the front of $STDIN to STDIN to gets.chomp and nothing seems to work.
$Health = 100
$OPHealth = 50
def fight
def NumberN
$RandomNumber = ran(0..30)
end
def Player
print ">"
PlayerMove = gets.chomp
if PlayerMove.downcase == "attack"
RandomNumber - OPHealth
puts "You attach the Spider and do #{RandomNumber} Damage,\n he has #{OPHealth}"
elsif OPHealth >= 0
puts "The SPIDER IS DEAD"
ENDGAME()
elsif Health >= 0
puts "Your dead GAMEOVER you abomination"
else
puts "You need to attack"
Player()
end
end
This particular issue will be with the case you're using: for variables, Ruby uses lower snake case.
Update your code's variables to use, for example: player_move = gets.chomp and this will resolve the error.
Using upper camel case as you are is reserved for classes and modules (with constants typically using upper case). (I'm sure I'm missing something here - let me know if anyone can correct me.)
Therefore, assigning values as you are is throwing the "dynamic constant assignment error" you mention.
Have a bit of a read up on this: global variables prefixed with $ are also seldom seen. This style guide is quite a good resource for this.
That said, simply updating the variables won't fix this in its entirety - you'll need to look at the the scoping and structure of your code before this will work. When you run into another issue, see how you get on and if you can't fix it, pop it into another question.

What does this operator #{var} do in ruby? [duplicate]

This question already has answers here:
Ruby question about # Signs
(2 answers)
Closed 7 years ago.
This is from a coderbyte solution to a problem that asks you to look at two integers and determine if there is any digit that occurs three times consecutively in the first number and twice consecutively in the second number. A user posted this solution (partial below), and I understand intuitively what their code is doing, but I'm not sure exactly how these #{i}'s work or what that operator is even called. Looking for more info.
It makes sense to me that you couldn't just say:
string.include?(iii) because that's just silly.
But what is the #{} doing exactly?
arr = num1.to_s.split("").uniq
arr.each do |i|
if num1.to_s.include?("#{i}#{i}#{i}") && num2.to_s.include?("#{i}#{i}")
return 1
end
end
The #{} allows you to execute ruby code within a string. For example,
puts "two plus two is #{2+2}. will give out the output "two plus two is 4." Be careful though, #{} will only work between double quotes and will not work between single quotes. In your example the #{i} will evaluate to the var i from arr.each do |i|
It's the string interpolation syntax: https://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Literals#Interpolation

What's the purpose of `do` in the while loop? [duplicate]

This question already has answers here:
Ruby while syntax
(2 answers)
Closed 7 years ago.
A while loop works with or without do. Please explain why the following two snippets works the same way.
Without do
i = 1
while i < 5
i = i + 1
end
With do
i = 1
while i < 5 do
i = i + 1
end
The non-theoretical answer is quite simply: because the Ruby Syntax Guide said so.
The language syntax guide defines the do keyword as optional for both while and until loops.
From what I understand - and it is mostly a theory - allowing the do to be optional rather than required is mostly for compatibility and allowing for harmonic syntax within the language.
I think of it as an acknowledgment for the "gray" areas, where things are less absolute. The same is done in physics, where light behaves both as a particle and as a wave and we should acknowledge both aspects.
Coming from different languages and school of thought, while is somewhere between a pure keyword (like if) and a method (like loop, which is defined under the Kernel module)
if statements do not require a do to begin a block of code and under the same logic, while loops wouldn't require a do keyword.
This is while as a keyword.
On the other hand, loop requires the do keyword (or the {block}), so why shouldn't while have the same semantics?
This is while as a method (as far as syntax goes).
Ruby is about making the programmer happy. Allowing the do to be optional makes all programmers happy and doesn't require that the Ruby programmer resign themselves to just one school of thought related to the nature of while.
x = 0
while x<3 do puts "hello"; x+=1 end
--output:--
hello
hello
hello
The do is optional, and can be used to clarify a code as in the answer to be on one line. Separation can be done with a do, newline, \, or semicolon.

Ruby syntax error with declarative concept of using variable [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I am trying to use the reactive programming concept in ruby, I have create two block of code:
1 Imperative
a = 5, b = 2
c = a + b
print c #=> 7
a = 2
print c #=> 7
2 Declarative
a := 5, b := 2
c := a + b
print c #=> 7
a := 2
print c #=> 4
However second example doesn't work for me and give the below error:
d.rb:1: syntax error, unexpected '=', expecting tSTRING_CONTENT or tSTRING_DBEG or tSTRING_DVAR or tSTRING_END
a := 5, b := 2
^
Please anyone help me to find out the error in the code. Any suggestion will be highly appreciated.
I know the second one is pseudo code but one thing surprise me that top score person make it off topic? The second code can also be executed using Reactive Library and top score programmer don't aware about it.
The := is not valid Ruby.
The error message is because symbols are represented by leading colons so :example is a symbol (compare to "example" which is a string).
So encountering : Ruby expects a valid beginning character for a symbol, which would be any of...
#$_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
Middle characters can be...
_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
And the last character can be...
!_=?ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
So = is never a valid symbol character.
The article you reference is showing pseudo-code not actual Ruby.

Ruby argument error [duplicate]

This question already has answers here:
Kernel#gets attempts to read file instead of standard input
(2 answers)
Closed 10 years ago.
If I hard code the variable max below, my program runs with no problems. If I pass an argument in, max sets correctly but gets throws and error. Why is that?
max = ARGV[0].to_i
# Ask user for first guess
puts "I am thinking of a number between 1 and " + max.to_s + "."
print "Make your guess: "
guess = gets.chomp.to_i
Error Thrown: `gets': No such file or directory (Errno:: ENOENT)
Note: The error is fixed by changing gets to STDIN.gets but why is this needed when without the argument my program works fine?
Further, is there a way to change the default behavior of gets back to STDIN.gets for the entire file? Perhaps with one line at the top of the program?
Kernel.gets has some interesting behavior that explains your issue:
http://www.ruby-doc.org/core-1.9.3/Kernel.html#method-i-gets
Specifically, it behaves differently depending on whether or not ARGV is empty, and if it is not empty then it will behave differently from STDIN.gets. If you don't want to use STDIN.gets explicitly, you might use max = ARGV.shift to remove that element before calling gets.
Addressing your last question: the best way to force gets' behavior to match STDIN.gets is probably to make sure ARGV is empty before doing anything else, and to make sure it stays that way. However, it may be wiser to continue to simply use STDIN.gets, "just to be sure". In cases like this, where unusual and surprising behavior is possible, it is almost always best to write code as explicitly as possible.
You should use:
STDIN.gets
When trying to get user input.

Resources