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.

Top comments (0)