サンプルコード。


$ cat ./simplelazy.rb
 
class TextArea
 
  def initialize(lines, font_size)
    @lines = lines
    @font_size = font_size
  end
 
  def height
    # すでに @height が設定されている場合はそれを返す
    # 設定されていなければ計算して @height に値をセットする
    # 計算は一度しか実行しない
    @height ||= calculate_height
  end
 
  def calculate_height
    $stderr.puts 'calculate_height'
    @lines.size * @font_size
  end
end
 
lines = [
  'Hello, world!',
  'This is a pen.',
  'My name is Pen',
]
 
textarea = TextArea.new(lines, 12)
puts "height=#{textarea.height}"
puts "height=#{textarea.height}"

実行結果。


$ ruby ./simplelazy.rb
calculate_height
height=36
height=36

参考資料。

自己代入

例:

foo += 12 # foo = foo + 12
a ||= 1 # a が偽か未定義ならば1を代入。初期化時のイディオムの一種。

Ruby 1.8.7 リファレンスマニュアル > 演算子式

ちなみに、環境。


$ uname -mrsv
Darwin 10.7.0 Darwin Kernel Version 10.7.0: Sat Jan 29 15:17:16 PST 2011; root:xnu-1504.9.37~1/RELEASE_I386 i386
 
$ ruby -v
ruby 1.8.7 (2009-06-12 patchlevel 174) [universal-darwin10.0]

tags: ruby

Posted by NI-Lab. (@nilab)