0

let say I have 2 arrays @arr1 = [10,20,30,40] @arr2 = [30,40,50,60]

In rails controller I am trying to find both diffs and according it add or remove records. If I do in console simple @diff1 = (@arr1 - @arr2) I get correct result [10,20]

if I do in rails controller the same, I get whole @arr1 instead of @diff1 so I tried simple puts (@arr1 - @arr2) but with wrong result here is the sample code:

@associates = params[:associate_to]
      @coordinators = @guild.coordinators.pluck(:coordinator_id)

      @to_add = (@associates-@coordinators)

      @to_remove = (@coordinators-@associates)
      puts "first array"
      puts @associates
      puts "----"
      puts "second array"
      puts @coordinators
      puts "-----"

      puts "calculation"      
      puts (@associates-@coordinators)
      puts "result"
      puts @to_add

and here is result from rails server

enter image description here

what am I doing wrong?

5
  • Can you try putting spaces around the minus sign? might be being interpreted oddly (ie as unary negative for some reason). @to_add = (@associates - @coordinators) Commented Feb 19, 2018 at 22:03
  • Also... when you use puts please use inspect - it can make all the difference. So: puts @associates.inspect and puts (@associates - @coordinators).inspect -> sometime's Rails implicit to_s can cause two different things to appear to be the same when they're really not. So do this now for all your putss and then show us the new results. Commented Feb 19, 2018 at 22:05
  • 2
    Also, since @associates comes from params and @coordinators comes from database records; It's very likely @associates is an array of strings while @coordinators is an array of integers. Maybe try @associates = params[:associate_to].map(&:to_i) Commented Feb 19, 2018 at 22:05
  • 1
    I bet on the good ol' String vs Integer comparison Commented Feb 19, 2018 at 22:06
  • 1
    Yup - that's why inspect is an excellent thing when using puts... it will instantly show you the difference... Commented Feb 19, 2018 at 22:32

1 Answer 1

1

It is probably because one array contains integers and the other contains strings. Try converting elements of one of the arrays to string or int.

arr.map(&:to_i)
# or
arr.map(&:to_s)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.