SitePoint Sponsor |
|
User Tag List
Results 1 to 4 of 4
Thread: Interfaces and Type Hinting?
-
Jun 29, 2009, 23:22 #1
- Join Date
- Sep 2004
- Location
- Toronto
- Posts
- 795
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Interfaces and Type Hinting?
I'm just starting out with Ruby and I've got a question about the OO features of the language.
Does Ruby support native interfaces, or do you need to code your own base or mixin setup?
And if you do manage to create a interface then is it possible to setup a type hint within a the parameters of a function to only allow a specific type of Class or Interface to be accepted?
sub someFunc(Class a)
end
Is this possible?I can't believe I ate the whole thing
-
Jun 30, 2009, 03:47 #2
- Join Date
- Feb 2006
- Location
- Worcs. UK
- Posts
- 404
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
I think your question relates to inheritance. You can create a new class based on an existing class very easily in Ruby. You can also mixin other code using modules
Code:class Animal def breath puts "Puff, puff" end end module FourLeggedAnimals def legs puts "4" end end class Dog < Animal include FourLeggedAnimals def bark puts "Woof, woof" end end dog = Dog.new dog.breath ---> "Puff, puff" dog.bark ---> "Woof, woof" dog.legs ---> "4"
Code:def get_something(something) # version that will only find Dogs if something.class == Dog # do dog only things elsif something.kind_of? Animal # do animal things else raise "Item is not an animal" end end
Code:dog = Dog.new dog.class == Animal ---> false dog.kind_of? Animal ---> true
http://www.ruby-doc.org/core/classes/Object.html
-
Jul 7, 2009, 12:14 #3
- Join Date
- Jul 2006
- Location
- Augusta, Georgia, United States
- Posts
- 4,194
- Mentioned
- 17 Post(s)
- Tagged
- 5 Thread(s)
I believe the answer to your question is duck typing.
-
Jul 9, 2009, 12:54 #4
- Join Date
- Jun 2004
- Location
- Copenhagen, Denmark
- Posts
- 6,157
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Bookmarks