2

I have 2 instance objects : @original_files and @version2_files

I want to retrieve the elements found in @original_files but NOT FOUND in @version2_files.

The code below:

<% @original_files.each do |original_file| %>

  <% @version2_files.each do |ver2_file| %>
    <% if original_file.name ==  ver2_file.name%>
      <%= original_file.name %> is common to both sets
      <% break %>
      <% else %>
    <% end %>
  <% end %>

<% end %>

I would appreciate it if someone could help me figure out how to find the elements found in @original_files only.

Thanks

Kim
  • 2,070
  • 5
  • 33
  • 46

3 Answers3

5

They are arrays? You can subtract...

@original_files - @version2_files

Hashes can use diff.

 @original_files.diff(@version2_files)   
danh
  • 62,181
  • 10
  • 95
  • 136
1

I understand this to mean that @original_files and @version2_files are hashes, and you want to find elements in @original_files that are not in @version2_files

@original_files.keys - @version2_files.keys
Jesse Wolgamott
  • 40,197
  • 4
  • 83
  • 109
1

disclaimer: new to ruby and may be ignorant of how hashes/arrays work exactly.

@danh's answer is right if you want to compare on key/value pairs. But if you're comparing the 2 hashes based on their values only and the keys are not important, then diff may not be what you need. In which case, you would do something like:

original.values - version2.values => [ ... ]

which returns an array of elements found only in original but not version2.

Also, this and this may help.

Community
  • 1
  • 1
vis
  • 2,279
  • 1
  • 19
  • 27