LoginSignup
5
5

More than 5 years have passed since last update.

DTを蝕む「Ruby脳」の恐怖

Last updated at Posted at 2013-03-22

まへがき

無意識だったわー このコード無意識で書いてたわー
——Zonu.EXE (24歳・中二病)

本文

このコードの == メソッドの定義を読んで違和感がなければRuby脳。

hoge_equals.rb
class Hoge
  attr_accessor :foo, :bar
  def initialize (arg)
    @foo = arg[:foo]
    @bar = arg[:bar]
  end
  def == (other)
    [self.foo, self.bar] == [other.foo, other.bar]
  end
end

fizz = Hoge.new(foo: "Foo", bar: "Bar")
bazz = Hoge.new(foo: "Foo", bar: "Bar")

p fizz == bazz
# => true

補足

  • タイトルで煽ってますが、このコードが問題視されることは、おそらく多くありません
    • Rubyの世界では 実行時に多少のオーバーヘッドがあったとしても、コードの書きやすさ、可読性が重視される文化だからです
    • 僕はさう思ってますが、Rubyistの間でも見解の差があるかもしれません (きっとある)
  • 他人の書いたPythonをあまり読んだことがないのですが、Pyの文化ではどうなのでせう…? (ちゃんと動きます)

解答に代へて

これをPHPに直訳すると、こんな (気持ち悪い) ことになります ヾ(#><)ノ゙

hoge_equals.php
<?php

class Hoge {
  public function __construct (array $arg) {
    $this->foo = $arg['foo'];
    $this->bar = $arg['bar'];
  }
  public function equals ($other) {
    return array($this->foo, $this->bar) == array($other->foo, $other->bar);
  }
}

$fizz = new Hoge(array('foo' => "Foo", 'bar' => "Bar"));
$bazz = new Hoge(array('foo' => "Foo", 'bar' => "Bar"));

var_dump($fizz->equals($bazz));
# => true

個人的な見解

言語デザインの力ってすごいよね
——tadsan (24歳・自称エンジニア)

一般的な模範解答

  • (self.foo == other.foo) && (self.bar == other.bar)
5
5
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5