Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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
self.split(//).sort_by{rand}.join
end
end

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

One-Liners

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!

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}