DEV Community

wuletaw wonte
wuletaw wonte

Posted on

Hash vs OpenStruct in Ruby

Hashes and OpenStructs are both data structures in Ruby that store key-value pairs. However, there are some key differences between the two.

Hashes are immutable. Once a hash is created, its keys and values cannot be changed. OpenStructs, on the other hand, are mutable. This means that you can add, remove, and change the keys and values of an OpenStruct after it has been created.

Hashes are more efficient. Hashes are a simpler data structure than OpenStructs, so they are more efficient. This means that they will perform better in terms of speed and memory usage.

OpenStructs are more flexible. OpenStructs are more flexible than hashes because they allow you to define arbitrary methods on the object. This makes them more powerful, but it also makes them less efficient.

In general, you should use a hash if you need a simple, efficient data structure. You should use an OpenStruct if you need a more flexible data structure that allows you to define arbitrary methods.

Here is an example of how to use a hash:


hash = {
  "name" => "Wuletaw Wonte",
  "age" => 30
}

puts hash["name"] # Wuletaw Wonte
Enter fullscreen mode Exit fullscreen mode

Here is an example of how to use an OpenStruct:

open_struct = OpenStruct.new(
  name: "Wuletaw Wonte",
  age: 30
)

puts open_struct.name # Wuletaw Wonte
Enter fullscreen mode Exit fullscreen mode

As you can see, the code for using a hash and an OpenStruct is very similar. However, the OpenStruct allows you to define the name and age methods, which makes it more flexible.

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay