别名与Ruby中的curried参数

时间:2014-03-13 00:36:40

标签: ruby-on-rails ruby

你可以在Ruby(以及可能的Rails)中使用curried参数别名一个方法吗?

def say(name)
  puts "Hi, I'm #{ name }"
end

alias_method :introduce_john, :say, "John"

introduce_john # puts "Hi, I'm John"

1 个答案:

答案 0 :(得分:1)

不是默认情况下,但很容易创建一个:

class Object
  def self.curried_alias_method(new, original, *pre_args)
    define_method(new) do |*args|
      send(original, *pre_args, *args)
    end
  end
end

用法:

class Foo
  def say(name)
    puts "Hi, I'm #{ name }"
  end

  curried_alias_method :introduce_john, :say, "John"
end

Foo.new.introduce_john
# prints "Hi, I'm John"