IV. Embed strings
One of the functions I like very much in Ruby is to embed strings. The so-called embed refers to the form of writing variables directly into quotes. The advantage of this is that it is intuitive and saves the frequency of hyphens. For example, in C# we can write the following code.
string val = "value"; string printVal = "value: " + val; // or string printVal = ("value: {0}", val);
val = "Value" printVal = "value: #{val}"
1module Company 2 class Employee 3 # Class variables 4 @@companyName = ".org" 5 # Member variables 6 @empId 7 8 def setEmpId(val) 9 @empId = val 10 end 11 12 def display() 13 # Braces omitted 14 print "Company: #@companyName\n" 15 print "Employee ID: #@empId\n" 16 # Braces cannot be omitted for pseudo-variables 17 print "lines: #{__LINE__}\n" 18 end 19 end 20end twenty one 22emp = Company:: ("001")
# Output as is # Company: #@@companyName print 'Company: #@companyName' # output as-is (including spaces and line breaks) print ' Company: .org Employee Id: unknown
Another cool feature of Ruby is the % rendering method, which is an alternative to quotes or other delimited characters. It is wrong to directly insert double quotes into double quotes in the first sentence below, but after rendering with % you can directly insert double quotes into the string.
# mistake print "Ruby"% presentation method"" # Apply % rendering method print %Q#Ruby "% rendering"#
# correct print %Q~Ruby "% rendering"~ print % "% rendering". print %Q*Ruby "% rendering"* # Insert rendering delimiter in % rendering print %Q*\* Ruby "% rendering"* # mistake print %Q** Ruby "% rendering"* print %QbRuby "% rendering"b print %Q<Ruby "% render"<
%Q substitute for double quotes => %Q#Ruby "% rendering"# is equivalent to "Ruby \"% rendering\""
%q replaces single quotes
%r replaces regular expression => %r#([\d\w/])*# is equivalent to /([\d\w\/)*/
%s invalidates embedded strings and symbols => print %s@#{__LINE__}@ output as is
%w Alternative string array
Previous page12345Next pageRead the full text