Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clearly compare old value with new one?

Tags:

ruby

A common piece of code that I already repeated some times, and never liked it, consists in save a value, do an action, and evaluate the value afterwards. Look at the following example

old_files = project.files
project.some_operation_dealing_with_files
if old_files == project.files
   puts "not changed"
else
   puts "changed"
end

One of the problems on it is that on the first line, when you read old_files = project.files, it is not clear where you want to get. I imagine that if I could eliminate that variable, the code would be better, but I don't know how to achieve this. I'm also, of course, open to suggestions.

TLDR; Is there a way to rewrite the code without the old_file variable?

like image 222
fotanus Avatar asked Nov 30 '25 21:11

fotanus


1 Answers

Make the object aware if the files state changes and provide a query method to test it. Set the did_change status to false at the start of each method that could change the files state.

project.some_operation_with_files
if project.files_did_change?
  puts "Changed"
else
  puts "No change."
end
like image 138
Fred Avatar answered Dec 02 '25 17:12

Fred



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!