0

I want to store ruby inject values into array I found one good example (on site http://matthewcarriere.com/2008/06/23/using-select-reject-collect-inject-and-detect/) but its returning Fixnum instead of array.

 [1,2,3,4].inject([]) {|acc,n| acc << n+n}

this is returning 262144. However I want array as [2, 4, 6, 8]. Any help is appreciated.

1 Answer 1

1

it works in my machine.

Have you tried it in a new irb session?

Which version of ruby are you using?

$ ruby  --version
ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-linux]

$ irb --version
irb 0.9.6(09/06/30)

$ irb
irb(main):001:0> [1,2,3,4].inject([]) {|acc,n| acc << n+n}
=> [2, 4, 6, 8]
irb(main):002:0> 
Sign up to request clarification or add additional context in comments.

4 Comments

version is same except mine is windows. basically I want array from this but its giving me error as: irb(main):001:0> (0..30).inject([1,0]) { |(i,j)| i << i+j } TypeError: nil can't be coerced into Fixnum from (irb):1:in +' from (irb):1:in block in irb_binding' from (irb):1:in each' from (irb):1:in inject' from (irb):1 from C:/Ruby23-x64/bin/irb.cmd:19:in `<main>'
You are trying to add an integer with an array. i + j => array + Fixnum. maybe you are trying to do this. (0..30).inject([1,0]) { |i,j| i << j +j }
oh you are correct, thanks I got why I am getting error. but I want to add previous number of array (i.e. i want to get fibonacci series till 30th position). I will really appreciate If you can guide.
(0..30).inject([0,1]) { |i| i << i[-1] + i[-2] }

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.