Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 18, 2021 03:00 am GMT

49 Days of Ruby: Day 22 - Duck Typing

Welcome to day 22 of the 49 Days of Ruby!

If you have been reading about Ruby, you might have come across a term called duck typing. Today we are going to spend some time discussing this idea and how it pertains to your code.

What is Duck Typing?

If it walks like a duck, then it is a duck.

Have you heard that expression before? If so, that's pretty much duck typing!

Ruby is less concerned about the type of a thing, and more about what it does. (We are going to cover types tomorrow!)

Take a look at the following example:

class Duck  def walk    puts "I'm walking"  endendclass Turkey  def walk    puts "I'm walking"  endend

Did you notice that both Duck and Turkey have a #walk method? Does that make a Turkey a Duck? Well, if we're following duck typing, then it really doesn't matter. As long as an Object responds to a method then that's all that really matters.

How do we check if it knows that method (or message, is another way of stating it)?

We can try the #respond_to? Ruby method, which does what it sounds like. It checks if an Object recognizes the message you are sending it. Continuing our example of a Duck and a Turkey:

> Duck.respond_to?(:walk)# => true> Turkey.respond_to?(:walk)# => true

They both know #walk so for all intents and purposes you can treat both the Duck and the Turkey as a Duck!

That's it for today! See you tomorrow as we discuss typing in Ruby.

Come back tomorrow for the next installment of 49 Days of Ruby! You can join the conversation on Twitter with the hashtag #49daysofruby.


Original Link: https://dev.to/bengreenberg/49-days-of-ruby-day-22-duck-typing-27h

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To