Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby when to use methods ! vs assigning the value back

Tags:

ruby

While working in Ruby I often find myself in a conflict between using methods with a ! or using a normal method as assign the value back. I am not sure when to use what. For example, I have 2 hashes (h1 and h2) and I want to merge them and store the value back in hash h1, now should I be using h1.merge!(h2) or h1 = h1.merge(h2)?

Is there any difference between the two?

like image 675
user2781725 Avatar asked Jul 04 '26 22:07

user2781725


1 Answers

Most of the time there is very little difference between h1.merge!(h2) and h1 = h1.merge(h2).

However, note that:

Since merge! modifies the old hash, you might be unintentionally affecting some other object in your program that holds a reference to that same hash. It is bad practice to modify a hash that you received as a method parameter because the caller usually does not expect it.

Using merge! is not functional programming, if you are a fan of that.

Using merge! is probably more efficient since it does not create a new hash, especially for large hashes.

I would use merge most of the time and only use merge! if I determine that it is safe and better.

like image 153
David Grayson Avatar answered Jul 07 '26 12:07

David Grayson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!