Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

225
Visualizações
How can I create a Generator in ruby?

How can I made this part of code from Javascript to Ruby? I would like to translate from Javascript to Ruby this function:

function* generate(arr) {
    console.log('AAAA'+ arr)
    const A = Array.from(arr); // copy
    const len = A.length;
    const c = new Array(len).fill(0);
    let i = 0;
    yield A;
  
    while (i < len) {
        if (c[i] < i) {
            let j = i & 1 ? c[i] : 0;

            if (A[i] != A[j]) {
                [A[j], A[i]] = [A[i], A[j]];
                yield A;
            }

            c[i]++;
            i = 0;
        } 
        else {
            c[i] = 0;
            i++;
        }
    }
};

I am using like this that function:

function* definition(data) {
    const state = data.map(v => generate(v));

and definition function i am using like this:

arr= [
  ['1','2','1','2','1'],
  ['2','2','2','4','4'],
]
state = definition(arr)
console.log('STATE',state)

this console getting this:

STATE[object Generator],[object Generator],[object Generator] the console show me this:

AAAA1,1,1,2,1
AAAA3,2,4,4,4
AAAA6,6,7,8,7

I was trying this is my attempt:

def generate(arr)      
  a = arr.clone
  len = a.size
  c = new Array(len).fill(0)
  let i = 0
  yield a

  while i < len 
    if(c[i] < i) 
      let j = i&1 ? c[i] : 0

      if (a[i] != a[j]) 
        a[j], a[i] = [a[i], a[j]]
        yield a
      end

      c[i]++
      i = 0
    else 
      c[i] = 0
      i++
    end
  end
end

In Ruby I am using like this:

def definition(data)
  state = data.map { |v| generate(v) }

But I need a function* in ruby to create a generator.

also, this new Array(len).fill(0) is ok?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Here JS generator function

function* generator() {
  let i = 0

  while (true) {
    yield i++
  }
}

gen = generator()

console.log(gen.next().value) // will print 0
console.log(gen.next().value) // will print 1
console.log(gen.next().value) // will print 2
// etc.

And here Ruby analogue to understanding

def generator
  Enumerator.new do |enum|
    i = 0

    loop do
      enum.yield i
      i += 1
    end
  end
end

gen = generator

puts gen.next # will print 0
puts gen.next # will print 1
puts gen.next # will print 2
# etc.
about 4 years ago · Juan Pablo Isaza Relatório

0

generator = Enumerator.new do |yielder|
  5.times do
    5.times do |i|
      yielder << i
    end
  end
end

generator.to_a
# => [0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4]
# Or use different methods from Enumerator or Enumerable
# Or make a function that returns this Enumerator for
# closest approximation of what you do with JS

In general, Ruby has no concept of * functions or async. You should think of them as if ALL Ruby functions were async and ALL calls were await. What this means is that unlike in JavaScript, in Ruby you can abort execution at any time, using a low-level interface of Fiber, or high-level abstractions like aforementioned Enumerator::Generator (created with Enumerator.new).

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda