From: andrew mcelroy Date: 2012-10-12T05:40:47+09:00 Subject: Re: Explanation of # and @#. --20cf307abcf9eb949204cbce95e5 Content-Type: text/plain; charset=ISO-8859-1 On Thu, Oct 11, 2012 at 3:33 PM, Muhammad Salman 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. > > 1 class Class > 2 def attr_access(*attrs) > 3 attrs.each do |attr| > 4 class_eval %Q{ > 5 def #{attr} > 6 @#{attr} > 7 end > 8 def #{attr}=(value) > 9 @#{attr} = value > 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 > class Foo > attr_access :a,:b > end > > Foo.instance_methods(false) #=> ["b=", "a=", "b", "a"] > > -- > Posted via http://www.ruby-forum.com/. > > --20cf307abcf9eb949204cbce95e5 Content-Type: text/html; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable

On Thu, Oct 11, 2012 at 3:33 PM, Muhamma= d Salman <lists@ruby-forum.com> 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. =A0

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

1 class Class=A0
2 def attr_access(*attrs)
3 =A0 =A0attrs.each do= |attr|
4 =A0 =A0 =A0class_eval %Q{
5 =A0 =A0 =A0def #{attr}
6 =A0= =A0 =A0 =A0@#{attr}
7 =A0 =A0 =A0end
8 =A0 =A0 =A0def #{attr}=3D(val= ue)
9 =A0 =A0 =A0 =A0@#{attr} =3D value
10 =A0 =A0 =A0end
11 =A0 =A0 }
12 =A0 =A0end
=A0 end
end


I numbered a few of the lines to make = this=A0easier=A0to 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 injec= tion happens anywhere you see #{}
after line 11 the previous 5 through 10 are evaluated.

<= /div>
try doing this in irb=A0
variable =3D "world"=
p "hello #{variable}"

you sho= uld see=A0
hello world

Hope this helps.

Andrew McElroy
=A0
class Foo
=A0attr_access :a,:b
end

Foo.instance_methods(false) #=3D> ["b=3D", "a=3D", &= quot;b", "a"]

--
Posted via http://= www.ruby-forum.com/.


--20cf307abcf9eb949204cbce95e5--