【问题标题】:How to translate code from Ruby to Javascript如何将代码从 Ruby 转换为 Javascript
【发布时间】:2015-01-30 17:55:43
【问题描述】:

我在这里有一段 Ruby 代码我想翻译成 Javascript,但我对这个过程不太熟悉,因为我还在学习。谁能翻译一下这个例子,对我的学习有很大帮助,谢谢!

    class TestFunky < MiniTest::Test
  def setup
    @funky = Funky.new
  end

  def test_adds_when_you_input_a_plus_5_6_plus
    assert_equal 11, @funky.push(5).push(6).push(:+)
  end

  def test_adds_when_you_input_a_plus_6_6_plus
    assert_equal 12, @funky.push(6).push(6).push(:+)
  end

还有一个

class NumberArray < Array
  def sum_or_multiply(operator)
    self.inject(operator)
  end

  def push(number)
    raise TypeError unless number.is_a? (Numeric)
    super
  end
end

class Funky

  def initialize
    @numbers = NumberArray.new
  end

  def push(something)
    if operator?(something)
      process_operator(something)
    else
      store(something)
      self
    end
  end

【问题讨论】:

  • 这有点棘手,因为 javascript 实际上使用函数来定义类。 javascript 中可能没有任何带有MiniTest::Test 的库。你可以尝试在这里查看一些东西developer.mozilla.org/en-US/docs/Web/JavaScript/…
  • @locoboy 不要太担心那部分,它的习惯,我只是想大致了解差异,所以我有一个指导方针。
  • 那么你到底想在这里评估什么?
  • 你能给出更具体的东西吗?如果你不关心继承,那么你应该把它拿出来。有些事情不符合您的目的,并希望确保您得到您正在寻找的东西。
  • 要在任意两种语言之间进行翻译,您需要能够同时编写这两种语言。所以简短的回答是:学习编写 Javascript。

标签: javascript ruby-on-rails ruby


【解决方案1】:

这是我认为您正在寻找的内容的粗略概念。

这些类定义基于Coffeescript implementation of classesMozilla guide on Object-Oriented Javascript

TestFunky = (function(_super) {
  function TestFunky() {
  }

  TestFunky.prototype = Object.create(_super.prototype);
  TestFunky.prototype.constructor = TestFunky;

  TestFunky.prototype.setup = function() {
    this.funky = new Funky();
  };

  TestFunky.prototype.testAddsWhenYouInputAPlus56Plus = function() {
    assert.equal(11, this.funky.push(5).push(6).push('+'));
  };

  TestFunky.prototype.testAddsWhenYouInputAPlus66Plus = function() {
    assert.equal(12, this.funky.push(6).push(6).push('+'));
  };

  return TestFunky;
})(MiniTest);

NumberArray = (function(_super) {
  function NumberArray() {
  }

  NumberArray.prototype = Object.create(_super.prototype);
  NumberArray.prototype.constructor = NumberArray;

  NumberArray.prototype.sumOrMultiply = function(operator) {
    this.inject(operator);
  };

  NumberArray.prototype.push = function(number) {
    if (typeof number !== 'number') {
      throw new Error();
    }
    _super.prototype.push.apply(this, arguments);
  };

  return NumberArray;
})(Array);

Funky = (function() {
  function Funky() {
    this.numbers = new NumberArray();
  }

  Funky.prototype.push = function(something) {
    if (this.operator(something)) {
      return this.processOperator(something);
    } else {
      this.store(something);
      return this;
    }
  };

  return Funky;
})();

一旦定义了这些,你就可以像这样实例化它们

var funkyInstance = new Funky()

【讨论】:

  • 谢谢丹尼尔,这就是我正在寻找的东西,它帮助我看到了不同之处。它为我澄清了很多事情。
猜你喜欢
  • 2014-11-22
  • 1970-01-01
  • 2012-02-25
  • 2022-12-02
  • 2021-12-24
  • 2012-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多