prabhu - 1 year ago 37

Ruby Question

I am trying to find whether

`n`

`true`

`false`

`inject`

`def sum_to_n?(array,n)`

array.each do |i|

array.inject(i) do |memo,var|

if memo + var == n

return true

else

return false

end

end

end

end

puts sum_to_n?([1,2,3,4,5],9)

Answer

Here is an approach :

```
def sum_to_n?(a,n)
!!a.find{|e| a.include?(n-e)}
end
a = [1,2,3,4,5]
sum_to_n?(a,9) # => true
sum_to_n?(a,11) # => false
```

If you want to get those 2 elements:

```
def sum_to_n?(a,n)
num=a.find{|e| a.include?(n-e)}
unless num
puts "not exist"
else
p [n-num,num]
end
end
a = [1,2,3,4,5]
sum_to_n?(a,9)
# >> [5, 4]
sum_to_n?(a,11)
# >> not exist
```

**Logic**

`Enumerable#find`

method passing one array element per iteration.Now for any iteration,say I have an element `e`

,and I subtracted it from n. Now I was just testing that `(n-e)`

is present in the source array.If I found a match `#find`

will stop finding,and immediately will return `e`

.If not found,then it will go for next iteration. If `#find`

completes its iteration,but didn't find `(n-e)`

,as per the documentation it will return `nil`

.