A
A
Anton2016-08-02 20:55:47
Ruby on Rails
Anton, 2016-08-02 20:55:47

Why is Ruby doing the condition wrong?

In general, there is such code:

test_var = false

# тут начинается цикл do |item|

  unless test_var
    test_var = item.present?
  end

# тут заканчивается цикл

Tried to debug his work:
test_var = false
array = []

# тут начинается цикл do |item|

  unless test_var
    test_var = item.present?
    array.push(test_var)
  end

# тут заканчивается цикл

render json: array

I get this:
[false,true,false,false]

Why is the condition still true after test_var becomes TRUE?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vlad Chernik, 2016-08-02
@vladchernik

I assume (because there is only a piece of code in the question) that your do end loop does not have any termination condition before the entire collection is iterated over. That is, your loop is executed even after the completion of the unless block, which is why the values ​​in the array are “not correct”.
One very smart person and a significant figure in the world of ruby ​​once told me:
In Ruby, if not everything, then a lot can be done elegantly, and sometimes even in one line.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question