Over a million developers have joined DZone.

Useful Rubyism's Part 1

DZone's Guide to

Useful Rubyism's Part 1

· ·
Free Resource

Ruby is the first language I have programmed in that makes me truly enjoy the development process. It's infinitely flexible, object-oriented, and has a lot of great Rubyism's that make it both unique and powerful. I will demonstrate a few of my favorite Rubyism's over the next few articles.

Class Method Overloading

Don't you just feel dirty every time you have to create a new class type in order to properly encapsulate a custom method that works with native tpes? Or even worse, if you're not into encapsulation, you create a helper function. Well, if you use Ruby, there are no worries. We can simply create our own class methods for the native class types or even overwrite existing class methods.

class String
def shuffle

puts "My Life Is Better Because of Ruby".shuffle
#=> "I iya sMeuB t r ceLoBtfeefuReybs"


Ruby is the king (or queen?) of one-liners. Because nearly everything in Ruby is object-oriented, you can basically write your entire program in one line of code! While that may be a bit extreme, creating one-liners can make your program much more readable and maintainable, especially if you're creating new methods as mentioned above.

#Convert sentence to CSV and capitalize each column
tbdata = "Ruby is awesome"
tbdata.split(/ /).map{|word| word.capitalize}.join(',')
#=> "Ruby,Is,Awesome"

More to Come!


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}