Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 14, 2021 01:55 pm GMT

Sharpen your Ruby: Hash

I develop in Javascript, Python, PHP and Ruby. By far Ruby is my favorite programming language.

Together let start a journey and revisit our Ruby foundations.

Each post will include some theory but also exercise and solution.

If you have any questions/comments or your are new and need help, you can comment below or send me a message.

What is a Hash

A Hash is a collection of key-value pairs for example: "product" => "price".

It is similar to an Array, except that indexing is done via a keys of any object type, not an integer index like array.

Create a Hash

Here how to create a Hash in Ruby

products = {'iPhone' => 699, 'iPad' => 799, 'Macbook Pro' => 1899}# or same but newer syntaxproducts = {'iPhone': 699, 'iPad': 799, 'Macbook Pro': 1899}

That's create a Hash with 3 entry (keys / values):
iPhone : 699
iPad : 799
Macbook Pro : 1899

You can search / access any item by specifying the key name

puts products[:iPad] # 799

You can search / access any item with default value if key not present

puts product.fetch(:iPhone, 0) # 699puts product.fetch(:iWatch, 0) # not found so 0

Remove item from a Hash

You can remove a item from a Hash with this syntax

products.delete(:iPhone)puts products # {"iPad"=>799, "Macbook Pro"=>1899}

Add item to a Hash

To add a new item just use this syntax

products[:iPad2] = 899puts products # {"iPad"=>799, "Macbook Pro"=>1899, :iPad2=>899}

Iterate over a Hash

To iterate over key/value pair

products.each do |key, value|   puts key  puts valueend

To iterate only over values

products.values.each do |value|   puts valueend

To iterate only over keys

products.keys.each do |key|   puts keyend

Array of Hash

Often you will have to work with an array of hash. Here an example:

products = [  {id: 100, name: 'iPhone12', price: 699},  {id: 200, name: 'iPad', price: 799},  {id: 300, name: 'iWatch', price: 899},]

It's a array so you can access an item like an array

product_1 = products[0]# {id: 100, name: 'iPhone12', price: 699}

You can extract info from hash like this

puts products[0][:price] # 699

Select only product with a price greater than 750$

high_price_products = products.select { | product | product[:price] > 750 }

Conclusion

That's it for today. The journey just started, stay tune for the next post very soon. (later today or tomorrow)

If you have any comments or questions please do so here or send me a message on twitter.

I am new on twitter so if you want to make me happy
Follow me: Follow @justericchapman


Original Link: https://dev.to/ericchapman/sharpen-your-ruby-hash-32kn

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To