Ruby Inject Weird Behavior

Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error Ruby Inject Weird Behavior on this date .

I’m trying to produce the full permutation of a given array. For example, if the input is fact(2, ['A', 'B']), the output should be [["A", "A"], ["B", "A"], ["A", "B"], ["B", "B"]].

def fact(n, arr)
    return [[]] if n == 0
    nxt = fact(n - 1, arr).freeze
    arr.inject([]){ |result, elem| nxt.each { |x| result.push(x + [elem]); result } }
end

However when I’m trying to do this using a ‘more functional programming’ way, something weird happened. The interpreter complains Untitled 4.rb:4:in 'push': can't modify frozen Array (RuntimeError). I’m actually trying to modify the injected array named result, how could it change nxt?

Answer

It’s built in, and it is lazy:

perms = ['A', 'B'].repeated_permutation(2)
#use the resulting enumerator like this:
perms.each{|perm| p perm}