Re-understanding Ruby polymorphism and Duck type

Source: Internet
Author: User

How is polymorphism defined in Java?

I understand this:

Polymorphism needs to be implemented by means of interfaces, that is, all classes that implement this particular interface are like him.

What is duck type?

This is defined in programming Ruby: If an object can walk like a duck and croak like a duck, then the interpreter will gladly treat it as a duck. (Programming Ruby Chinese version P367)

One day I asked a colleague if there was a polymorphism in Ruby.

Get an interesting answer: weak type of dynamic language, no abstract class, no interface, you say there is no polymorphism?

Polymorphism is very useful, polymorphism is not only static object-oriented language such as java/c# and so on? Of course not, one of the three characteristics of the polymorphic oo language.

Ruby is a purely object-oriented language, and Ruby is of course polymorphic. Ruby's Polymorphic property is its duck type.

Don't say much, put code

Ruby Code

class SimpleFilter
  attr_reader :fltr_expres
  def initialize(fltr_expres)
  @fltr_expres = fltr_expres
end
def apply_filter(value)
  value.include?(@fltr_expres)
end
end
class RegexFilter
  attr_reader :fltr_expres
  def initialize(fltr_exprs)
  @fltr_expres = fltr_exprs
end
def apply_filter(value)
  value =~ @fltr_expres
end
end
# SimpleFilter和RegexFilter这两个类并不共享一个基类
# 在单元测试中对两个类的实例组成的集合进行迭带
# 简单的调用同名的"apply_filter()"方法就轻松实现了多态
# ruby没有接口,只要方法名匹配,就能轻松的实现了多态特性
require 'test/unit'
class FilterTest < Test::Unit::TestCase
def test_filters
  fltrs = [SimpleFilter.new('oo'), RegexFilter.new(/Go+gle/)]
  fltrs.each do |fltr|
  assert(fltr.apply_filter('I love to Google'))
end
end
end

In Ruby, class is never (almost never) a type, whereas an object type is based on what the object can do, that is, the object's behavior (method).

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.