※ 引述《contagious (布穀飽吃不堡)》之銘言:
[恕刪]
: 另外, Ruby 根本不擔心型態的問題,
: 只要物件能完成要求的動作就好了。
: 這就是所謂 Duck Typing。
關於 Duck Typing 的解說,可以看這篇
http://en.wikipedia.org/wiki/Duck_typing
In computer science, duck typing is a term for dynamic typing typical of
some programming languages, such as Smalltalk, where a variable's value itself
determines what the variable can do. It also implies that an object is
interchangeable with any other object that implements the same interface,
regardless of whether the objects have a related inheritance hierarchy.
Duck Typing 代表的意思是讓 variable 的 value 決定他的type,而非強制去定義他們。
這也代表每個 variable 可以跟其他的物件交換,因為他們都有一個共用的 Interface
而不是去定義首棟另外一個 interface 。
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 61.230.115.163
> -------------------------------------------------------------------------- <
作者: contagious (布穀飽吃不堡) 看板: Ruby
標題: Re: [分享] 另一個 Parallel Assignment 玩法
時間: Thu May 25 02:54:36 2006
另外, Ruby 根本不擔心型態的問題,
只要物件能完成要求的動作就好了。
這就是所謂 Duck Typing。
比如說這個例子:
class Cat
def speak
puts 'meow'
end
end
class Dog
def speak
puts 'woff'
end
end
def talk_to_me (obj)
obj.speak
end
talk_to_me(Cat.new)
talk_to_me(Dog.new)
Cat 和 Dog 都有 speak 這個 method,所以他們都能完成 talk_to_me 所需要的功能。
不用去建立 interface 或是繼承架構來強迫他們是同一種「型別」。
不過要是那一天我傳了一個不會 speak,
或是有 speak method 但是做的是完全不同的事的東西進去怎麼辦?
所以你一定要寫 Unit Test
其實這裡在講的就是 Static Typing 和 Dynamic Typing 的爭議
可以參考 wikipedia 的說明 http://en.wikipedia.org/wiki/Type_system
只是想不到 parallel assignment 竟然會扯到 Typing 的問題..
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 61.224.49.91