Immutable Object is Useful

github logo ・1 min read

From some talk videos I watched this style of code, Let's start with a simple example:

class Fish
  def initialize(age)
    @age = age

  def say()
    "My age is #{@age}"

fish =
fish.say() #=> My age is 3

This is called immutable or functional object. It's solid and cannot be broken after created.

Then how to change the age in sample?

class Fish
  def with_age(age)

fish.with_age(5).say() #=>My age is 5

This code style is fun and useful. It'll reduce the change of object.

What's your idea?

twitter logo DISCUSS
Classic DEV Post from Dec 22 '18

How does your workplace approach recognition?

Does your workplace have a strategy for recognising team members?

chenge profile image
Ruby, and learn Rust, Go, Elixir, Erlang...

Need a change? now has dark mode.

Go to the "misc" section of your settings and select night theme ❤️