Eustaquio 'TaQ' Rangel
3/26/2008 2:33:00 PM
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
| I want to add together numbers in an array with the inject command. I
| want only the even numbers using only inject.
| So, something like [1,2,3,4].inject.....but don't know what to do so
| help!
Use select before inject:
[1,2,3,4,5,6].select {|i| i%2==0}.inject {|m,v| m+v}
You could use a test to sum the number only when it's even on inject, but
[1,2,3,4,5,6].inject {|m,v| m + (v%2==0?v:0) }
results to 13, because seems that the value of m is automatically the first
element of the array. On this case, you can tell it to start with 0:
[1,2,3,4,5,6].inject(0) {|m,v| m + (v%2==0?v:0) }
| Second, I need to reverse an array using only the inject command. So,
| something like above with the result [4,3,2,1]
Why don't you use reverse?
[1,2,3,4,5,6].reverse
Regards,
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.7 (GNU/Linux)
iD8DBQFH6l6Hb6UiZnhJiLsRAjwlAJ9NGeatugJ2r9b/VJGWy7dUrTmXAACghLOA
Vfmi0X7wtEArwWQmgMshhmo=
=qKJi
-----END PGP SIGNATURE-----