Explanation of # and @#

I am relatively new to Ruby. In the below code which redefines the
attr_accessor method i cannot understand the #{attr} and @#{attr}. I
know # as comment and @ as required for a instance variable in Ruby.

class Class
def attr_access(*attrs)
attrs.each do |attr|
class_eval %Q{
def #{attr}
@#{attr}
end
def #{attr}=(value)
@#{attr} = value
end
}
end
end
end

class Foo
attr_access :a,:b
end

Foo.instance_methods(false) #=> [“b=”, “a=”, “b”, “a”]

On Thu, Oct 11, 2012 at 3:33 PM, Muhammad S.
[email protected]wrote:

I am relatively new to Ruby. In the below code which redefines the
attr_accessor method i cannot understand the #{attr} and @#{attr}. I

Those are string interpolation.

know # as comment and @ as required for a instance variable in Ruby.

10 end
11 }
12 end
end
end

I numbered a few of the lines to make this easier to talk about.
line 4 starts of an eval note the %Q which roughly means double quote
this
string.
lines 5- 10 are basically in a string. from there the string
interpolation
/ variable injection happens anywhere you see #{}
after line 11 the previous 5 through 10 are evaluated.

try doing this in irb
variable = “world”
p “hello #{variable}”

you should see
hello world

Hope this helps.

Andrew McElroy

On 12/10/2012, at 9:33 AM, Muhammad S. [email protected] wrote:

I am relatively new to Ruby. In the below code which redefines the
attr_accessor method i cannot understand the #{attr} and @#{attr}. I
know # as comment and @ as required for a instance variable in Ruby.

%Q{
def #{attr}
@#{attr}
end
def #{attr}=(value)
@#{attr} = value
end
}

The # symbol when used with {} is for string interpolation, e.g…

f = “world”
puts “hello #{f}”

%Q is another way of defining a string with interpolation, e.g.

f = %Q{world}
puts “hello #{f}”

Henry

greeting = ‘hello’
my_string = “#{greeting} world”
puts my_string

–output:–
hello world

attr = ‘color’
my_string =<<ENDOFSTRING
def #{attr}
@#{attr}
end
ENDOFSTRING

puts my_string

–output:–
def color
@color
end

The syntax #{expression} allows you to inject a value into a double
quoted string. Just like any other character ‘@’ can be a character in
a double quoted string.

Oh, yeah…%Q is just another syntax for double quotes:

verb = ‘yelled’
puts %Q{He #{verb}, “It’s all Ruby!”}

–output:–
He yelled, “It’s all Ruby!”