Leon's Blogging

Coding blogging for hackers.

Ruby - Alias vs Alias Method

| Comments

Diff

  • alias 可以重命名全局變數 alias_method 不可以
  • 關鍵字與方法的不同
  • 參數不同
  • 作用域不同

alias

  • 建立 method 的別名
  • 可以別名全域變數
  • libdoc 之下的 RDoc 裡的關鍵字
  • 可使用 method namesymbol
  • scope 只在其關鍵字存在的scope
1
alias new old
1
2
3
4
5
6
7
8
9
10
11
class User
  def hi
    'hi'
  end

  alias hello hi
end

user = User.new # => #<User:0x007fedc406afe0>
user.hi         # => "hi"
user.hello      # => "hi"

另外也可以別名全域變數

1
2
3
4
$a = 1
alias $b $a
$b
# => 1

scope

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Animal
  def say
    'hi'
  end

  def self.add_hi
    alias :hi :say
    # scope 只在 Animal,因此會是 hi
  end
end

class Dog < Animal
  def say
    'hello'
  end
  add_hi
end

Dog.new.hi # => "hi"

alias_method

Makes new_name a new copy of the method old_name. This can be used to retain access to methods that are overridden.

  • 是 module 類別的一個方法
  • 可以是 stringsymbol
  • 要有 , 區隔
  • scope 可以到父類別繼承下來的 method
1
alias_method new old
1
2
3
4
5
6
7
8
9
10
11
class User
  def hi
    'hi'
  end

  alias_method :hello, :hi
end

user = User.new # => #<User:0x007fcb8e0c8a08>
user.hi         # => "hi"
user.hello      # => "hi"

將原本的 exit 別名為 orig_exit,再將原本的 exit method 覆蓋

1
2
3
4
5
6
7
8
9
module Mod
  alias_method :orig_exit, :exit
  def exit(code=0)
    puts "Exiting with code #{code}"
    orig_exit(code)
  end
end
include Mod
exit(99)

scope 在 當前

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Animal
  def say
    'hi'
  end

  def self.add_hi
    alias_method :hi, :say
    # scope 到繼承類別,say 被 Dog 覆蓋掉,因此會是 hello
  end
end

class Dog < Animal
  def say
    'hello'
  end
  add_hi
end

Dog.new.hi # => "hello"

Sorting, the JavaScript way

在 js 當中,sort 會先轉成 string 在做排序

1
2
[-2, -1, 0, 1, 2].sort()
// [-1, -2, 0, 1, 2]

ruby 則是

1
2
[-2, -1, 0, 1, 2].sort
# [-2, -1, 0, 1, 2]

利用 alias_method 讓 ruby 排序跟 js 一樣

1
2
3
4
5
6
7
8
9
module JSSort
  def self.included(base)
    base.alias_method :old_sort, :sort
  end

  def sort
    self.map(&:to_s).old_sort.map(&:to_i)
  end
end
1
2
3
Array.include(JSSort)
Range.include(JSSort)
(-2..2).sort

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
module TestJson
  def self.included(base)
    base.alias_method :old_to_json, :to_json
  end

  def to_json
    puts 'hiiii'
  end
end

class Test
end

Test.include(TestJson)
Test.new.to_json

參考文件

Comments