I am quite new to Ruby and always assumed these two notations were an identical way to interpolate instance variables until I noticed the difference in the example code below for the 'vendor' parameter.
class Component
def initialize(name, version)
@vendor = "vendor"
@name = name
@version = version
puts "#{@vendor}-@#{name}-@#{version}"
end
end
ConfiguredComponent.new("param1", "param2")
=> this works
class Component
def initialize(name, version)
@vendor = "vendor"
@name = name
@version = version
puts "@#{vendor}-@#{name}-@#{version}"
end
end
ConfiguredComponent.new("param1", "param2")
=> using @#{vendor} notation does't work => :in 'initialize': undefined local variable or method `vendor' for # (NameError)
class Component
def initialize(name, version)
@vendor = "vendor"
@name = name
@version = version
puts "#{@vendor}-#{@name}-#{@version}"
end
end
Component.new("param1", "param2")
=> this also works
It's the
#{(expression)}
that's significant.If the expression is
#{name}
then that's substituting the variablename
which in all your examples comes from the parameters input into the method.If the expression is
#{@name}
then that's substituting the variable@name
which is defined in the fourth line of your methods.@#{name}
is not a special construct. It's just the string@
followed by the contents of the variablename
.The reason it didn't work in your second example is that you simply haven't defined a variable
vendor
.