Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

245
Views
¿Cómo puedo reemplazar palabras en una cadena con elementos en una matriz en Ruby?

Estoy tratando de reemplazar palabras (secuencia de caracteres, en general) en una cadena con los valores correspondientes en una matriz. Un ejemplo es:

"The dimension of the square is {{width}} and {{length}}" con la matriz [10,20] debería dar

"The dimension of the square is 10 and 20"

He intentado usar gsub como

 substituteValues.each do |sub| value.gsub(/\{\{(.*?)\}\}/, sub) end

Pero no pude hacerlo funcionar. También he pensado en usar un hash en lugar de una matriz de la siguiente manera:

{"{{width}}"=>10, "{{height}}"=>20} . Siento que esto podría funcionar mejor, pero nuevamente, no estoy seguro de cómo codificarlo (nuevo en Ruby). Cualquier ayuda es apreciada.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Puedes usar

 h = {"{{width}}"=>10, "{{length}}"=>20} s = "The dimension of the square is {{width}} and {{length}}" puts s.gsub(/\{\{(?:width|length)\}\}/, h) # => The dimension of the square is 10 and 20

Vea la demostración de Ruby . Detalles :

  • \{\{(?:width|length)\}\} - una expresión regular que coincide
    • \{\{ - una {{ subcadena
    • (?:width|length) : un grupo que no captura que coincide con palabras de width o length
    • \}\} - una }} subcadena
  • gsub reemplaza todas las apariciones en la cadena con
  • h : utilizado como segundo argumento, permite reemplazar las coincidencias encontradas que son iguales a las claves hash con los valores hash correspondientes.

Puede usar una definición hash un poco más simple sin { y } y luego usar un grupo de captura en la expresión regular para que coincida con la length o el width . Entonces necesitas

 h = {"width"=>10, "length"=>20} s = "The dimension of the square is {{width}} and {{length}}" puts s.gsub(/\{\{(width|length)\}\}/) { h[Regexp.last_match[1]] }

Vea esta demostración de Ruby . Entonces, aquí, (width|length) se usa en lugar de (?:width|length) y solo el Grupo 1 se usa como clave en h[Regexp.last_match[1]] dentro del bloque.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!