Cat and mouse become best friends. Unexpected..

3 Unexpected Behaviors using Ruby

Tech - RubyCademy
RubyCademy

--

In this article we’re going to explore the following topics:

  • return values within an ensure clause
  • variables declared in a conditional block
  • String#to_i vs Integer(String)

Introduction

In Ruby, what I call an unexpected behavior is a behavior that doesn’t seem natural at first.

This means that with a bit of knowledge about what happens behind the scene. we are able to understand the purpose of these choices.

In this article we’re going to break down 3 examples of unexpected behaviors using Ruby.

Return values within an ensure clause

In Ruby, the value of the last evaluated statement is used as return value of the called method if there is no explicit call to return

Here, the result of the 21 + 21 operation is used as return value of the add method.

That’s why a call to the add method returns 42.

But, what happens when the last statement of an ensure clause is evaluated?

The last evaluated statement of the henry.hello('TJ Dillashaw') method call is the "hello #{@name}" string interpolation within the ensure clause.

So we’d expect the call to henry.hello('TJ Dillashaw') to return "hello TJ Dillashaw".

But, it returns "TJ Dillashaw" which is the result of the @name = name assignation.

So, we have to explicitly use the return keyword if we want to return the value of the ensure clause

Variables declared in a conditional block

Variables declared in a conditional block that is never evaluated are initialised with a default nil value

Here, the champ variable is initialized with a nil value even though the content of the if conditional block is never evaluated.

In this case, we’d expect the following error to be raised:

NameError (undefined local variable or method `champ’ ..)

This behavior is due to the fact that your Ruby code must first be parsed before it can be run.

It’s at this stage that the behavior you’re experiencing originates.

As the parser scans through the code, whenever it encounters a variable declaration then it allocates space for that variable by setting its value to nil.

String#to_i vs Integer(String)

The String#to_i method is used to convert the string representation of a number to an Integer

It works as expected.

But what if the string that calls the to_i method is not the representation of a number ?

Here we can see that "a string".to_i returns 0.

We’d expect this method call to return nil — or to raise an error.

To do so, we can use the Kernel#Integer() method.

This method raises a TypeError if the passed string is not strictly conformed to numeric representation

Ruby Mastery

We’re currently finalizing our first online course: Ruby Mastery.

Join the list for an exclusive release alert! 🔔

🔗 Ruby Mastery by RubyCademy

Also, you can follow us on x.com as we’re very active on this platform. Indeed, we post elaborate code examples every day.

💚

--

--