Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR RUBY

ruby different ways to run string interpolation

# TECHNIQUE 1 - standard interpolation
name = 'david'

# standard interpolation using double quiote is not lazy, it evaluates straight away
"who is #{name}"
# => who is david

# TECHNIQUE 2 - % instead of # can be used with lazy or late evalutation 
'who is %{name}' % { name: name }
# => who is david

# TECHNIQUE 3 - use eval/binding (from the Facets GEM) also supports  - % instead of # can be used with lazy or late evalutation
def interpolate(&str)
  eval "%{#{str.call}}", str.binding
end

interpolate { "who is #{name}" }
# => who is david
Source by github.com #
 
PREVIOUS NEXT
Tagged: #ruby #ways #run #string #interpolation
ADD COMMENT
Topic
Name
1+7 =