ruby - 方法中临时变量的惯用 ruby

标签 ruby scope encapsulation idioms

在一个方法中,我在计算其他变量时使用ij 作为临时变量。一旦不再需要 ij,有什么惯用的方法可以摆脱它们?我应该为此目的使用 block 吗?

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

背景:我想在不再需要 ij 时摆脱它们,这样它们就不会被使用通过方法中的任何其他代码。减少我的代码出错的机会。我不知道这个概念的名称——它是“封装”吗?我能想到的最接近的概念是(警告:TV Tropes 的链接——工作时不要访问)Chekhov'sGunYouHaveOutlivedYourUsefulness .

另一种选择是将代码放入他们自己的方法中,但这可能会降低可读性。

最佳答案

是什么让您认为将代码拆分为多个方法会损害可读性?根据我的经验,即使是中小型代码也可以拆分成多个方法,这样可以大大提高可读性。

关于ruby - 方法中临时变量的惯用 ruby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2870492/

相关文章:

c++ - 什么时候我应该更喜欢非成员非 friend 函数而不是成员函数?

ruby - Prawn PDF : render a set of things on the same page

ruby-on-rails - 如何干燥重复的 Ruby 代码?

ruby-on-rails - 如何用一条 Haml 线放置一条记录的多个属性

scope - 错误: "use of moved value"

c++ - esms.cpp :234: error: 'the_config' was not declared in this scope

JavaScript 循环返回意外结果

c++ - 数据封装(网络编程)

c++ - 声明后添加好友类

ruby-on-rails - ruby on rails i18n 和 number_to_currency 负值