user3111432
user3111432

Reputation: 81

Ruby Inject Weird Behavior

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?

Upvotes: 1

Views: 64

Answers (2)

steenslag
steenslag

Reputation: 80065

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}

Upvotes: 3

user3111432
user3111432

Reputation: 81

Turn out to be a typo.

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

Upvotes: 1

Related Questions