LoginSignup
4
0

More than 5 years have passed since last update.

Ruby でメソッドを入れ替える

Last updated at Posted at 2017-09-27

メソッドを入れ替える swap_memthods を作りました

kiminonaha.rb
module Kernel
  def swap_methods(a, b)
    alias_method :__temp__, a
    alias_method a, b
    alias_method b, :__temp__
    remove_method :__temp__
  end
end

class Kiminonaha
  def taki
    puts "もしかして俺たち..."
  end

  def mitsuha
    puts "もしかして私たち..."
  end

  def say
    taki
    mitsuha
    puts "「「入れ替わってる~!?!?!?」」"
  end
end

Kiminonaha.new.say

普通に実行

もしかして俺たち...
もしかして私たち...
「「入れ替わってる~!?!?!?」」

swap_methods を追加して実行

    def say
      taki
      mitsuha
      puts "「「入れ替わってる~!?!?!?」」"
    end

+   swap_methods :taki, :mitsuha
  end
もしかして私たち...
もしかして俺たち...
「「入れ替わってる~!?!?!?」」

「入れ替わってる〜 :fearful:

使い所は無いです。

4
0
0

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
4
0