Idiomatic ruby ​​for temporary variables inside a method

As part of the method, I also use iit jas temporary variables when calculating other variables. What is the idiomatic way to get rid of iand jwhen 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 would like to get rid of iand jwhen they are no longer needed so that they are not used by any other code in the method. Gives my code fewer chances to make a mistake. I don’t know the name of the concept - is it "encapsulation"? The nearest concepts that I can think of (warning: links to TV Tropes - do not visit while working) Chekhov'sGun or YouHaveOutlivedYourUsefulness .

, .

+3
5

Ruby ( JS) ( ++ ..). Ruby 1.9 :

last_nucleotide_position = nil
proc { |;i, j|
  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
}.call()

. ruby ​​1.9?. , , (, last_nucleotide_position).

FM , .

+2

, ? , .

+4

, , , - , i j. . - .

, , , . , .

def calc_first_nucleotide_position(po)
  i = po.first
  while nucleotide_at_position(i-1) == nucleotide_at_position(i)
    raise "Assumption violated" if i == 1
    i -= 1
  end
  i
end

# etc...

first_nucleotide_position = calc_first_nucleotide_position(positions)
last_nucleotide_position  = calc_last_nucleotide_position(positions)

# etc...
+2

Ruby Lisp let. Ruby , , :

x = 10
scope { |x|
    x = 30
}
puts x #=> 10

.: http://banisterfiend.wordpress.com/2010/01/07/controlling-object-scope-in-ruby-1-9/

+1

, , , 1.times. , , . , , , .

y = 20
1.times do
  # put your code in here
  i = 1
  puts x = y # => 20, because y is available from outside the block
  y = 'new value' # We can change the value of y but our changes will 
    # propagate to outside the block since y was defined before we opened
    # the block.
end

defined? i # => nil, i is lost when you close the block
defined? x # => nil, x is also local to the block
puts y # => 'new value'
+1

Source: https://habr.com/ru/post/1746299/


All Articles