Skip to content

Instantly share code, notes, and snippets.

@plusor
Created July 29, 2013 14:21
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save plusor/6104625 to your computer and use it in GitHub Desktop.
Save plusor/6104625 to your computer and use it in GitHub Desktop.
alias 和 alias_method 区别 ruby
alias 和 alias_method 区别 ruby

1

class User

  def full_name
    puts "Johnnie Walker"
  end

  alias name full_name
end

User.new.name #=>Johnnie Walker
  • 这两个例子中 alias 不需要逗号,还有冒号(或者双引号)
class User

  def full_name
    puts "Johnnie Walker"
  end

  alias_method :name, :full_name
end

User.new.name #=>Johnnie Walker

2


class User

  def full_name
    puts "Johnnie Walker"
  end

  def self.add_rename
    alias_method :name, :full_name
  end
end

class Developer < User
  def full_name
    puts "Geeky geek"
  end
  add_rename
end

Developer.new.name #=> 'Gekky geek'
  • 这两个例子中可以看出作用域不同,alias是进入原类进行操作,而alias_method是查找当前类同名方法进行操作
class User

  def full_name
    puts "Johnnie Walker"
  end

  def self.add_rename
    alias :name :full_name
  end
end

class Developer < User
  def full_name
    puts "Geeky geek"
  end
  add_rename
end

Developer.new.name #=> 'Johnnie Walker'
@molizz
Copy link

molizz commented May 8, 2014

赞一个

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment