Ruby has much in common with functional programming languages. For example, Ruby supports high-order functions, lambdas, currying and recursion, but not the immutability - Ruby’s types and data structures are mutable and can be changed at any time.
Why immutability is important? The’re many arguments for that:
- simpler debugging
- purity - immutable data allows you to write side-effects free code
If you want to make Ruby hash immutable, you can use freeze it:
But if you want to use already immutable collections, sets and other data structures, you can try Hamster library.
Hamster provides efficient, immutable and thread-safe collection classes for Ruby, such as Hash, Vector, Set, SortedSet and List. Hamster collections offers Ruby`s Hash, Array, Enumberable compatibility where it possible. You can require all of Hamster collection classes:
or only certain types:
If you want to use immutable data structures in Ruby to write more reliable, efficient and at the same time thread-safe code, you can take a look at Hamster. You can find more in Hamster’s API documentation.