Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR RUBY

ruby string interpolation lazy evaluation

name = 'david'

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

# using single quote does not evaluate 
'who is #{name}'
# => who is #{name}

# TECHNIQUE 1 - % instead of #
'who is %{name}' % { name: name }
# => who is david

# TECHNIQUE 2 - use eval/binding (from the Facets GEM)
def interpolate(&str)
  eval "%{#{str.call}}", str.binding
end

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