Ad space (banner)
๐Ÿ’ŽRuby Lessons
Lesson 51 / 68

Methods That Work with Any Type

In this lesson you will learn to write generic methods that take advantage of Ruby being dynamically typed. This is for anyone searching for "what is Ruby dynamic typing".

Ruby is a dynamically typed language, so a method can generally accept a value of any type. Writing a method that does not commit to one type lets you reuse the same logic for numbers and for strings.

The sample code has larger(a, b) handle both numeric and string comparison with the same logic. The > operator compares magnitude for numbers and dictionary order for strings, so one method serves both.

A common stumbling block for beginners is what happens when an unexpected type arrives. The flexibility comes at a cost: no error is raised and a defect can follow, so pairing it with a type check is safer. The respond_to? method also lets you ask whether an object has a particular method.

Ruby's "everything is an object" philosophy is what lies behind this flexibility. In real design work, balancing that flexibility against safety is the important part.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Ruby directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)