Idiomatic ruby for temporary variables within a method

Posted by Andrew Grimm on Stack Overflow See other posts from Stack Overflow or by Andrew Grimm
Published on 2010-05-20T01:25:54Z Indexed on 2010/05/20 1:30 UTC
Read the original article Hit count: 449

Within a method, I am using i and j as temporary variables while calculating other variables. What is an idiomatic way of getting rid of i and j once they are no longer needed? Should I use blocks for this purpose?

i = positions.first
while nucleotide_at_position(i-1) == nucleotide_at_position(i)
  raise "Assumption violated" if i == 1
  i -= 1
end
first_nucleotide_position = i
j = positions.last
while nucleotide_at_position(j+1) == nucleotide_at_position(j)
  raise "Assumption violated" if j == sequence.length
  j += 1
end
last_nucleotide_position = j

Background: I'd like to get rid of i and j once they are no longer needed so that they aren't used by any other code in the method. Gives my code less opportunity to be wrong. I don't know the name of the concept - is it "encapsulation"? The closest concepts I can think of are (warning: links to TV Tropes - do not visit while working) Chekhov'sGun or YouHaveOutlivedYourUsefulness.

Another alternative would be to put the code into their own methods, but that may detract from readability.

© Stack Overflow or respective owner

Related posts about ruby

Related posts about variable-scope