Less errors? Well, it does magic stringification, if that's what you mean.
It also does less work (I'm pretty sure each
String#+ call
creates a new string object, which doesn't happen with interpolation.)
Here's the version of your line using interpolation for the outer string:
@f += "\t<label for=\"
#{
@h["s_fieldname_" + i.to_s]
}
\">
#{
@fieldname.capitalize
}
:"
And then, b
ecause
the stuff inside the interpolated block is Ruby code, you can interpolate
in there too, if you really want:
@f += "\t<label for=\"
#{
@h["s_fieldname_
#{i}
"]
}
\">
#{
@fieldname.capitalize
}
:"
If you're not entirely comfortable with the nested interpolation, there's
nothing wrong with temporary variables:
h = @h["s_fieldname_#{i}"]
@f += "\t<label for=\"
#{
h
}
\">
#{
@fieldname.capitalize
}
:"
And then, if you want fewer backslashes throughout, you can use the
alternative syntax for string literals[1]:
@f +=
%(
\t<label for="
#{
@h["s_fieldname_
#{i}
"]
}
">
#{
@fieldname.capitalize
}
:
)
# OR
h = @h["s_fieldname_#{i}"]
@f +=
%(
\t<label for="
#{
h
}
">
#{
@fieldname.capitalize
}
:"
)
... but that's strictly optional. Also consider `
@f << ...
` if you prefer to modify the string object in-place rather than creating a
new one.
There are many ways to achieve what you want; it comes down to personal
taste, requirements, and maintainability.
Cheers
[1]:
https://ruby-doc.org/core-2.3.0/doc/syntax/literals_rdoc.html#label-Percent+Strings
···
On 3 September 2016 at 00:08, Bee.Lists <bee.lists@gmail.com> wrote:
Hi folks. I come from a language where we don’t have string
interpolation. Here’s what I would usually write:
@f += "\t<label for=\"" + @h[("s_fieldname_" + i.to_s)].to_s + "\">" +
@fieldname.capitalize + “:"
Now I’ve been told there are less errors with string interpolation. How
can I translate that? I get hung up on the internal bit here:
@h[("s_fieldname_" + i.to_s)
I’m sure it’s out there. I appreciate any input.
Cheers, Bee
--
Matthew Kerwin
http://matthew.kerwin.net.au/