Crystal tuples: the immutable data structure of crystal


Bookmark and Share

Tuple is a data structure which has immutable elements and is of a fixed size. Its similar to an array, but unlike arrays in crystal and ruby which allows adding more values over time a tuple is of fixed and cannot change. (Disclaimer: This article is meant for Ruby developer and explaining what a tuple is to a ruby developer).

In crystal we have two types of tuple

1) Tuple {1, “hello”, :world}
2) NamedTuple {x: 1, y:2, z: 5}

They are immutable, which means if you try changing the value of an element in a tuple you will get an exception. Since crystal programs are compiled before execution you will get to see these errors while you compile the program itself.

example:

If you try assigning a value to it, like so

You will get an exception like bellow.

In crsytal, tuples are the preferred way to return a multiple results from a method.

For example inside the crystal core we have a method to get the minimum and maximum of an array.

the result would be {1, 100}

Note: Since we just mentioned minmax, have a look at minmax_by method as well. It would let you apply a block of code over your range and then …

Read More

Lambda vs Proc Vs Blocks


Bookmark and Share

The difference between these three is one of the most baffling concepts to grasp while anyone starts to learn ruby. Since at Red Panthers we recruit and build our own team from freshers, we too will be blogging about it here to make it easy for the beginners.

But before we state the difference between the three, let me explain what all these three does to make it easy for you.

Blocks: They are called closures in other languages, it is a way of grouping code/statements. In ruby single line blocks are written in {} and multi-line blocks are represented using do..end

An interesting fact about ruby is that all methods in ruby accept a block, even if you don’t declare a variable to accept it. So for example, take the method below

It can accept a block as below

The code is valid, but the output will have only puts “Hello World”.

Why? because we passed in the block but it is not getting called. To run the block passed within your method you need to use the yield command.

Now it will print

But since we placed yield, it would now be expecting a block to be always passed in. So we need to …

Read More