Understanding Counts by Ruby Branch

Asked 2 years ago, Updated 2 years ago, 39 views

Using X as a variable, +1or-1 is added according to the conditions of の, and when the bias of X becomes +5or-5, it is shifted to or or に.Also, I would like to write a code saying that it will be reset and looped again when I move to 、 and に and meet the conditions, but it doesn't work.
So far, I've written it in an atmosphere, but it doesn't work the way I want, is there a good way?Thank you for your cooperation.

loop do
X=0
--------------------------------------------------------------------- (1) if baldness
X=X-1
elsif baldness X=X+1
----
if X>5
X=X-5
------------------------------------------------- <
if X<-5
X=X+5

end

ruby

2022-09-30 17:16

1 Answers

As pointed out in the comment section, if you initialize X in the loop, X will initialize to 0 every time the loop returns, so let's initialize X outside the loop.
Also, to make X 0 when the value of X is +5, -5, we can simplify it to make X 0 when the absolute value of X is 5.(ruby can post if statements, called if modifiers)

X=0
loop do
  if hoge
    X = X+1
  elsifuga
    X = X-1
  end

  X = 0 if X.abs == 5
end

By the way, it is very difficult to read because there is no end in the code of the question sentence that pairs the if statement.


2022-09-30 17:16

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.