• 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

昨日に引き続きIntegerに関して。 個人的に、Integerブームが起こってます。

Integerに関しては、http://www.ruby-doc.orgのClass: Integerを参照のこと。

今日は最大公約数と最小公倍数を同時に返してくれるInteger#gcdlcmについてです。

このInteger#gcdlcmの実装が気に入らない!!

どこが気に入らないのかという本題に入る前に、Integer#lcmについての実装を見てみよう!

   1  # File lib/rational.rb, line 457
   2    def lcm(other)
   3      if self.zero? or other.zero?
   4        0
   5      else
   6        (self.div(self.gcd(other)) * other).abs
   7      end
   8    end

オーソドックスなの最小公倍数の求め方。 ここではあまり問題にしない。

このコードをよーく覚えておいてください。

ここからが本題です。

Integer#gcdlcmの実装を見て見る。

   1  # File lib/rational.rb, line 473
   2    def gcdlcm(other)
   3      gcd = self.gcd(other)
   4      if self.zero? or other.zero?
   5        [gcd, 0]
   6      else
   7        [gcd, (self.div(gcd) * other).abs]
   8      end
   9    end

Integer#lcmにそっくり!

・・・って、Integer#lcmのコードにInteger#gcdいれただけじゃないですか・・・。

せっかくこのコードの直前で、Integer#lcmを定義してるのに、何で使わないんやろうか・・・。

   1  def gcdlcm(other)
   2    return [self.gcd(other), self.lcm(other)]
   3  end

という風に書いても不都合はなさそうやけど・・?

むしろ、こういう風に書いてくれたほうが、気持ちいいんやけども。

ん~、Integerには謎がいっぱいや。

posted by Png y_tsuda on Fri 15 Aug 2008 at 04:06
Contents
Integer#gcdlcmの実装が気に入らない
Comments
Aleksey: The uname check is only due to a somewhat slopp... '11-2
Yu Tsuda: あぁ、そうですね、、syncすると戻ってしまいますね・・・。 ご指摘ありがとうございます!! '09-7
ursm: /usr/portage 以下のファイルは更新のたび元に戻ってしまうので、/etc/porta... '09-7
Yu Tsuda: 見た目だけでも、わざわざGentooをこういうリストに入れてるのがすごいなぁと思ったりしたので... '09-3
Leonard Chin (レオ): ただし、VirtualBoxで「Gentoo」などを選択しても、別にどのOSを入れても大丈夫だ... '09-3
Services from s21g
twpro(ツイプロ)
Twitterプロフィールを快適検索
地価2009
土地の値段を調べてみよう
MyRestaurant
自分だけのレストラン手帳
Formula
ブログに数式を埋め込める数式コミュニティ