Para no oxidarme quiero refrescar mis conocimientos de rubí puro resolviendo algunos algoritmos. No puedo resolver un algoritmo más grande sin resolver uno más pequeño como el siguiente ejemplo.
Haga que la función falta_dígito(str) tome el parámetro str , que será una fórmula matemática simple con tres números, un solo operador (+, -, *, or /) y un signo igual (=) y devuelva el dígito que completa el ecuación. En uno de los números de la ecuación, habrá un carácter x , y su programa debe determinar qué dígito falta. Por ejemplo, si str es "3x + 12 = 46" , entonces su programa debería generar 4 .
Examples Input: "4 - 2 = x" Output: 2 Input: "1x0 * 12 = 1200" Output: 0Creo que encontré la solución para python pero no puedo encontrar el código Ruby correspondiente en ninguna parte.
Python y Ruby son bastante similares, aunque intentar convertir esto sin un TDD básico hubiera sido difícil. Aquí está el archivo convertido a Ruby de su ejemplo de python. Refactorizaría este código, pero las pruebas simples aquí pasan, las que se dan en su ejemplo vinculado.
class StringMathX def self.calculate(str) exp = str.split() first_operand = exp[0] operator = exp[1] second_operand = exp[2] resultant = exp[-1] # If x is present in resultant if resultant[/x/] first_operand = first_operand.to_i second_operand = second_operand.to_i if operator == '+' res = first_operand + second_operand elsif operator == '-' res = first_operand - second_operand elsif operator == '*' res = first_operand * second_operand else res = first_operand / second_operand end return res end # If x in present in operands # If x in the first operand if first_operand == 'x' x = first_operand.to_i second_operand = second_operand.to_i if operator == '+' res = resultant - second_operand elsif operator == '-' res = resultant + second_operand elsif operator == '*' res = resultant / second_operand else res = resultant / second_operand end # If x is in the second operand else x = second_operand.to_i first_operand = first_operand.to_i if operator == '+' res = resultant-first_operand elsif operator == '-' res = first_operand - second_operand elsif operator == '*' res = resultant.to_i / first_operand.to_i else res = first_operand.to_i / resultant.to_i end end res = res.to_s k = 0 for i in [*0..x] if i == x result = res[k] break else k += 1 end end result.to_i end end require 'minitest/autorun' require_relative '../lib/string_math_x' class StringMathXTest < Minitest::Test def test_basic_subtration input = '4 - 2 = x' assert(StringMathX.calculate(input) == 2, 'outputs 2') end def test_whats_up_returns_doc input = '1x0 * 12 = 1200' assert(StringMathX.calculate(input) == 0, 'outputs 0') end end Para ejecutar esto, es posible que necesite gem install minitest
Luego ejecute ruby test/test.rb
def findx(str) s = str.sub('=', '==') i = s.index('x') pre = s[0,i] post = s[i+1..-1] ('0'..'9').find { |d| eval(pre+d+post) rescue nil }&.to_i end findx("4 - 2 = x") #=> 2 findx("1x0 * 12 = 1200") #=> 0 findx("3**x = 81") #=> 4 findx("1/x == 2.0").nil? #=> true se necesita rescue nil en caso de que se realice una división por cero. & es el operador de puerto seguro . Devuelve nil , sin tener en cuenta todo lo que sigue, si la parte anterior devuelve nil .