Ruby & Rails

Ruby中的动态方法

2018-03-23  本文已影响20人  柳辉

一、什么是动态方法?
这就要从静态语言和动态语言的区别说起,静态语言比如Java,在编译阶段就需要运行对象调用的所有方法,而动态语言,只需要真正调用方法的时候才运行这个方法。

举个例子:

class box
  def open_1
    puts "hello"
  end
  def open_2
    puts "world"
  end
end

box = Box.new
box.send('open_#{num}')

上面是用Ruby写的“打开不同魔法盒,就显示不同的字“的需求
用静态语言写,就要这样写:

class box
  def open(num)
    case num
      when 1;puts("hello")
      when 2;puts("world")
    end
  end
end

box = Box.new
box.open(1)

二、为什么要用动态方法?

三、怎么用动态方法?
直接在对象后面加上动态方法,参数是静态方法名

资料来源:
https://ruby-china.org/topics/4313
https://blog.csdn.net/u011345213/article/details/42167763

上一篇 下一篇

猜你喜欢

热点阅读