Black Bytes
Share this post!

All posts by Jesus Castello

ruby oop

Stop Using Case Statements in Ruby

Are you using the full power of OOP (Object-Oriented Programming) or are you missing out?

If you are taking decisions based on the type of an object then you are missing out on one important OOP feature: polymorphism.

Type decisions are usually done inside case statements (which are not OO friendly) & in this article you will learn how to write better code by removing them.

Checking For Types

Let me start by showing you an example where we don’t take advantage of polymorphism.

We want to implement the “Rock, Paper, Scissors” game & we have decided to have one Game class and one class for every possible move.

To check for a winner we are going to implement a play method on Game:

And here is one of the moves (the others follow the same pattern):

Now we can call the play method with two moves & we will know if the first move wins.

Ok, this is working, but can we do better? Can we get rid of that ugly case statement?

Polymorphism Instead of Type Checking

Yes! We can get rid of the type-checking case statement by using OOP fundamentals.

The idea is to use the fact that we know the current class to ask the other movement object if it can beat us.

And we are going to use a method name that is specific to our class (for Rock the method name could be: do_you_beat_rock?)

In Ruby, polymorphism is the ability to send any method calls (also know as messages, in OOP parlance) to any object without having to check the object’s class. This is also known as “duck typing”, but I don’t like that term 🙂

In Java (bear with me for a second…), you have something called “interfaces” which allows you to force a set of methods to be implemented by a class at the compiler level.

We don’t have that in Ruby (probably for the better), so you will have to rely on testing.

Let’s see a code example of what this new implementation looks like:

Notice how the case statement is gone. It has been replaced by a single method call & two method definitions.

Update: As some readers have commented, I didn’t notice that the logic is reversed when implementing this pattern. One proposed solution by Daniel P. Clark is to just flip the order in the play method to move2.wins_against?(move1).

Isn’t this a lot cleaner? What do you think?

One More Move!

Now let’s say you want to add a new move. What would you have to change?

Think about it for a minute…

With the case statement approach you have to add a new branch to every move. Notice that you are “forced” to change a perfectly working method to introduce new functionality.

But that’s not an issue with our more OOP oriented version. All we have to do is add new methods. This is the open/closed principle (the “O” in SOLID) in action.

Another option could be to use metaprogramming (with method_missing or define_method).

Would I actually use metaprogramming for this?

Probably not, unless the number of moves is changing constantly, or there is a big number of moves.

There is a cost to metaprogramming, it’s not a silver bullet like some people may believe. You would be trading performance & readability for a bit of extra flexibility.

Conclusion

In this article you learned that you should avoid using case statements to check for class types. Instead, you should take advantage of polymorphism.

This will help you create better code that can be extended by adding new code instead of changing existing code. Now it’s your turn to take action & do some refactoring 🙂

Don’t forget to share this article if you want me to keep writing articles like these!

Ruby Under The Hood: Memory Layout of an Object

If you enjoy seeing how things work under the hood I think you are going to love this post…

…because we are going to explore together how a Ruby object is laid out in memory & how you can manipulate that to do some cool stuff.

So fasten your seatbelts because this is going to be quite a journey into the depths of the Ruby interpreter.

Memory Layout of Arrays

When you create an array, Ruby has to back that up with some system memory & a little bit of metadata (like the array size). Since the main Ruby interpreter (MRI) is written in C there are no objects, but there is something else: structs.

A struct in C helps you store related data together, and this is used a lot in MRI’s source code to represent things like Array, String‘s & other kinds of objects.

By looking at one of those structs we can infer the memory layout of an object.

So let’s look at the struct for Array, called RArray:

I know this can look a bit intimidating if you are not familiar with C, but don’t worry! I will help you break this down into easy to digest bits of info 🙂

The first thing we have is this RBasic thing, which is also a struct:

This is something that most Ruby objects have & it contains a few things like the class for this object & some binary flags that say if this object is frozen or not (and other things like the ‘tainted’ attribute).

In other words: RBasic contains the generic metadata for the object.

After that we have another struct, which contains the length of the array (len).

The union expression is saying that aux can be either capa (for capacity) or shared. This is mostly an optimization thing, which is explained in more detail in this excellent post by Pat Shaughnessy. In terms of memory allocation, the compiler will use the biggest type inside an union.

Then we have ptr, which contains the memory address where the actual Array data is stored.

Here’s a picture of what this looks like (every white/grey box is 4 bytes in a 32-bit system):

array memory layout

You can see the memory size of an object using the ObjectSpace module:

Now we are ready to have some fun!

A Fun Experiment

RBasic is exactly 8 bytes in a 32-bit system & 16 bytes in a 64-bit system. Knowing this we can use the Fiddle module to access the raw memory bytes for an object & change them for some fun experiments.

For example:

We can change the frozen status by toggling a single bit. This is in essence what the freeze method does, but notice how there is no unfreeze method.

Let’s implement it just for fun!

First, lets require the Fiddle module (part of the Ruby Standard Library) & create a frozen string.

Next, we will need the memory address for our string, which can be obtained like this:

Finally, we flip the exact bit that Ruby checks to see if an object is frozen. We also check to see if this worked by calling the frozen? method.

Notice that the index [1] refers to the 2nd byte of the flags value (which is composed of 4 bytes in total).

Then we use ^= which is the “XOR” (Exlusive OR) operator to flip that bit. We do this because different bits inside flags have different meanings & we don’t want to change something unrelated.

If you have read my ruby tricks post you may have seen this before, but now you know how it works 🙂

Another thing you can try is to change the length of the array & print the array. You will see how the array becomes shorter! You can even change the class to make an Array think it’s a String

Conclusion

You have learned a bit about how Ruby works under the hood. How memory for Ruby objects is laid out & how you can use the Fiddle module to play around with that.

You should probably not use Fiddle like this in a real app, but it’s fun to experiment with.

Don’t forget to share this post so more people can see it 🙂

ruby stack

Practical Computer Science in Ruby: Using Stacks to Solve Problems

If you don’t have a CS (Computer Science) degree you might feel like you are missing out on something… Or you may feel like CS is too abstract to be useful… Or that Ruby already does all the hard work for you…

In this post I want to show you one practical computer science concept that you can start putting into practice right now!

The Stack

A stack is a data structure which you can use as a “to-do” list. You keep taking elements from the stack & processing them until the stack is empty.

Here’s is a visual representation.

Push 5 into an empty stack:

5

Push 3 into the stack:

3
5

Push 9 into the stack:

9
3
5

Take one item from the stack:

3
5

The big thing to notice here is that new items are added to the top of the stack. In a “Last-In First-Out” (LIFO) fashion. Meaning that when you take (pop) an item from the stack, it will be the last item that was pushed into it.

Another way to visualize how this works is by thinking about a stack of plates. If you put one plate on top of another you can’t take out the bottom plate without taking out the top plate first.

That’s all you are doing with a stack, pushing things to the top or poping things out. There is no indexing.

Let’s see some code examples on how this can be used.

Example 1 (flatten)

One classic example is to flatten an array. In other words, convert a multi-dimensional array into a one-dimensional array.

In Ruby we have the flatten method which does this for you. But what if you didn’t have this method? And how does this method work?

This is where the stack comes in!

Ruby implements the push & pop methods, so we can treat an array like a stack.

Note: Both push & << are the same method. I will be using << in my code examples.

The idea is to go over every element and check if it’s an array or something else. If it’s an array then we will push the elements inside this array back into the stack.

What happens is that we keep removing array layers (like an onion) until there are none left. This will leave us with a flattened array.

Here’s is the code:

You will notice there is no pop method call in this code. This is because I’m letting each do the hard work of taking the items from the stack & feeding them to my algorithm. Also notice how the order of the elements is not mantained when doing things this way.

Another version using until & empty?:

Since we are using pop now, instead of letting each do its thing, we are getting the flattened array in the correct order… But in reverse.

This reveals an interesting property of stacks:

Whatever list of things you put in, it will come back in the same order but in reverse.

Tip: The Array#flatten method takes an argument, which lets you define how many layers of nesting you would like to remove (by default all of them).

Example 2 (balanced parenthesis)

Here is another example, where there is no equivalent Ruby method to do everything for you. And it’s also another classic problem in computer science: matching balanced parenthesis.

The idea is that you are given a string & you need to validate if the parenthesis make sense.

For example, let’s say you are writing a math evaluation program. You want to make sure the input is valid before processing it.

Example (Valid Input):

Example (Invalid Input):

You can use a stack to keep track of any parenthesis you have found in the input & then when you find a new parenthesis you check the top of the stack to make sure it matches the closing parenthesis.

If there is no match that means that you have invalid input.

Example:

Another thing you will notice is that I ended this valid_parentheses method with a stack.empty?. That’s to make sure we don’t end with unclosed parenthesis.

If all the parenthesis are correctly closed then the stack should be empty 🙂

Example 3 (directions)

One more example to make sure you understand how to apply this.

In this case we are given a set of directions & we are told that we need to optimize it to save our traveler some time.

Here is an example set:

You will notice that if you go north then south you will end up in the same place (assuming it’s the same distance both directions). So that’s what we need to optimize & we can do that using a stack.

Example:

Conclusion

I hope you learned something new & that you start looking for ways to use stacks to solve programming challenges.

Don’t forget to share this post so more people can read this!

ruby equality

How to Make Your Classes More Powerful by Implementing Equality

How do you compare two things in Ruby? Using == as you already know… but did you know that == is a method & not just syntax?

You can implement this method in your own classes to make them more powerful. And that’s what I want to talk about in this post.

Equality Basics

As you know you can compare two strings like this:

And if the content is equal then this will evaluate to true. This works because the String class implements a == method that knows how to compare strings.

But what if String didn’t implement ==?

Then Ruby would use Object‘s implementation of ==, which defaults to testing for object identity, instead of object contents.

Example:

Implementing Equality

Now let’s use what you just learned to make your own classes more powerful by being able to compare them.

Thanks to the == method you can define exactly what it means for two instances of your own class to be equal.

Example:

The == method says that both the name and the price must be the same for two Product objects to be considered equal.

Remember:

If you don’t implement this method (or use the Comparable module, which I explain in my Ruby book) the two objects will be compared using their object id’s, instead of their values.

Also I should mention that if you use a Struct it already implements == for you.

What About Triple Equals?

You may be wondering if == is a method, is === also a method? And the answer is yes 🙂

So what’s the difference between the two?

In Javascript there is a clear difference, where == will try to convert the object types to be the same if they aren’t (1 vs '1'). And === is for ‘strict’ equality.

But in Ruby there is not such thing. What === means depends on the class implementing it.

In many cases it is just an alias for ==.

Like in String and Object.

Here’s a table of built-in classes which give === a special meaning:

Class Meaning
Range Returns true if obj is an element of the range, false otherwise.
Regexp Match regexp against a string.
Module Returns true if obj is an instance of mod or and instance of one of mod’s descendants.
Proc Invokes the block with obj as the proc’s parameter like Proc#call. It is to allow a proc object to be a target of a when clause in a case statement.

Conclusion

In this post you learned how to make your classes more powerful by implementing the == method. You also learned the difference between == and ===.

Don’t forget to share this post so more people can see it 🙂

15 Weird Things About Ruby That You Should Know

15 Weird Things About Ruby That You Should Know

By Jesus Castello

Ruby is an amazing language with a lot of interesting details that you may not have seen before...

…in this post I compiled some of those details for your own enjoyment in a nice-looking list :)​

1

Heredoc + Method

If you have some data that you want to embed into your program you may want to use a “heredoc”.

Like this:

This will give you a string. But you may want to do some post-processing, like splitting this string into an array of strings.

Ruby lets you do this:

Bonus tip:
Ruby 2.3 introduced the "squiggly heredoc" <<~. This will remove all the extra spaces introduced by indentation, which is a common problem when using heredocs for text.

2

Call a Method Using Double Colon

Apparently this is a thing…

3

Puts with Multiple Arguments

Pretty simple, but could be useful in some situations I guess.

4

Infinite Indexing

Example:

This works because [] is just a method & it keeps returning the first character, which is also a string.

5

De-structuring Block Arguments (or whatever you want to call this)

Want to get rid of some local variables? You will love this trick!

This has the same effect as if we did this:

But it saves you one line of code 🙂

6

Special Global Variables

When you use a regular expression with capture groups it will set the global variable $1 to the first group, $2 for the second group, etc.

The thing about these is that they don't behave like normal variables. They are ‘method-local’ & ‘thread-local’, as described by the documentation.

Also they can’t be directly assigned to like regular global variables.

7

Shovel Method on Strings

There is this “shovel” method on string which doesn’t do what you would expect when you use it with a number

…it’s interpreting the number as an ASCII character.

Here’s another way to do that:

8

Character Literals

Not sure if there are any practical uses for this one…

Let me know in the comments what you think 🙂

9

The RbConfig Module

RbConfig is a module which is not documented & it contains some info about your Ruby installation.

There is some useful info under RbConfig::CONFIG (like compile flags, ruby version & operating system).

10

Spaces, Spaces Everywhere!

You can put as many spaces as you want between a method call & the receiver of that call.

Yes, this is valid Ruby syntax 🙂

11

Infinite Nesting of Constants

You can have an infinite amount of nested constants like this:

The reason this works is that all top-level constants (defined outside any class) are contained in the Object class & every class inherits from Object by default.

Try Object.constants to see what I mean.

12

Chaining the Shovel Operator

You can chain the shovel << operator multiple times:

13

BEGIN & END

Two keywords that you don’t see very often are BEGIN & END. I believe these come from the Perl / Unix world, where it’s common to write short scripts for processing output from other programs.

Let’s see an example of how this works:

This code will print "Program starting..." before it prints 123. It could be useful if you are writing the kind of short scripts that this is meant for, but probably not very useful in web applications.

Update:
Reader Ronald sent me some interesting uses for this trick. Here is what he said:

"It is very useful, for example for fiddling with the RUBYLIB path for the 'require' statements, because it is guaranteed to be executed before all the 'require'. I also use it to set $VERBOSE to true, or set some environment variables, etc."

14

Flip-Flop

I don’t even know why this is a thing, but I would advice to stay away from it because it can be confusing & most people are not familiar with this feature 🙂

But it could be useful to know in case you find this in other people’s code.

This is the syntax:

The idea is that once the first condition is true an invisible “switch” will turn on & everything from there will evaluate as true until the 2nd condition is true.

Example:

This prints all the numbers from 3 to 15, but if you skip 15 it will keep printing.

15

Redo Keyword

Another keyword that you don’t see very often is redo, this allows you to repeat the same iteration inside a loop…

…but unless you use next or break you will have an infinite loop. So I think you should not use this feature.

Conclusion

You learned about a few cool Ruby tricks & tips. If you want more see my other post here.

Don’t forget to share this post so more people can see it!

1 2 3 19