Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby string substitution

Tags:

ruby

Don't know what the term is called (substitution?), but in python if you type

num1 = 4  
num2 = 2  
print("Lucky numbers: %d %d" %(num1, num2))

You get "Lucky numbers: 4 2"

How do I do this in ruby?

Trying to do the above scenario, it works if I have one variable, but if I need to sub in multiple variables the parentheses aren't valid syntax.

like image 584
MxLDevs Avatar asked Apr 27 '12 20:04

MxLDevs


People also ask

How do you replace a string in Ruby?

Ruby allows part of a string to be modified through the use of the []= method. To use this method, simply pass through the string of characters to be replaced to the method and assign the new string.

What does GSUB do in Ruby?

gsub! is a String class method in Ruby which is used to return a copy of the given string with all occurrences of pattern substituted for the second argument. If no substitutions were performed, then it will return nil. If no block and no replacement is given, an enumerator is returned instead.

How do I remove special characters from a string in Ruby?

In Ruby, we can permanently delete characters from a string by using the string. delete method. It returns a new string with the specified characters removed.

What is .TR in Ruby?

Ruby | Matrix tr() function Return Value: It returns the trace.


2 Answers

You can use something called string interpolation in Ruby to accomplish this.

ex:

num1 = 4  
num2 = 2  
puts "Lucky numbers: #{num1} #{num2}";

Here each variable that is inside the #{} is interpreted not as a String but as a variable name and the value is substituted.

like image 166
Hunter McMillen Avatar answered Sep 17 '22 17:09

Hunter McMillen


num1 = 4  
num2 = 2  
print "Lucky numbers: %d %d" % [num1, num2]
like image 22
steenslag Avatar answered Sep 20 '22 17:09

steenslag