RubyµÄself
selfÉÏÏÂÎÄ
RubyµÄselfÓкÍJavaµÄthisÏàËÆÖ®´¦£¬µ«ÓÖ´ó²»Ïàͬ¡£JavaµÄ·½·¨¶¼ÊÇÔÚʵÀý·½·¨ÖÐÒýÓã¬ËùÒÔthisÒ»°ã¶¼ÊÇÖ¸Ïòµ±Ç°¶ÔÏóµÄ¡£¶øRubyµÄ´úÂëÖðÐÐÖ´ÐУ¬ËùÒÔÔÚ²»Í¬µÄÉÏÏÂÎÄ(context)self¾ÍÓÐÁ˲»Í¬µÄº¬Ò壬ÏÈÀ´¿´¿´³£¼ûµÄcontext self¶¼´ú±íÄÄЩ
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# Õâ¸öλÖÃλÓÚtop level context£¬´ú±íObjectµÄĬÈ϶ÔÏómain
p self # => main
p self.class # => Object
@self1 = self
# ÒòΪËùÓÐ×Ô¶¨ÒåÀ඼λÓÚmain contextÖ®ÖУ¬ËùÒÔÕâÊÇObjectµÄʵÀý·½·¨
# ͬʱҲ¿ÉÒÔ˵ÊÇÒ»¸öÈ«¾Ö·½·¨
def a_method
@self2 = self
p self
# => main£¬ÒòΪÓÐÁËʵÀý±äÁ¿@self1ºÍ@self2£¬ËùÒÔ´òÓ¡³öÀ´µÄ²»ÊÇmainÕâ¸ö×Ö·û
# => µ«ÈÔÈ»ÊÇmain¶ÔÏó£¬×¢Ê͵ô4£¬8Ðм´¿É¿´µ½Ð§¹û
p @self1 == @self2 # => true
end
# ÏÂÃæÊÇÒ»¸ö¹ØÓÚÀàÖв»Í¬ÉÏÏÂÎĵÄself
class Person
p self # => Person£¬´ú±íµ±Ç°Àà
def instance_method
p self # => #<Person:0xb7818fdc>£¬´ú±íµ±Ç°ÀàµÄʵÀý
end
def self.class_method
p self # => Person£¬ºÍµÚ16ÐÐÒ»Ñù´ú±íµ±Ç°ÀࣨÕâÊÇÀà·½·¨µÄcontext£©£¬ËüÃÇÊÇÏàµÈµÄ
end
end
m = Person.new
def m.hello
p self # => ´ú±ímÕâ¸öµ¥Àý¶ÔÏó
end
m.hello
ÉÏÃæÖ»Ð´ÁËÔÚÀàÖеÄself£¬ÆäʵÔÚmoduleÒ²ÊÇÒ»ÑùµÄ¡£Í¨¹ýÉÏÃæ´úÂëÄã¿ÉÒÔ·¢ÏÖ£¬selfÒ»Ö±ÒýÓÃ×ÅËüËùÔÚλÖÃÉÏÏÂÎĵÄʵÀý/Àà¡£
selfÏÔʽ/Òþʽ
Äã¿ÉÒÔÏÈÊÔ×ÅÔËÐÐÏÂÃæ´úÂ룬¿´¿´ÓÐʲôÒâÍâ·¢ÉúûÓÐ
1
2
3
4
5
6
7
8
9
10
11
12
13
class Person
attr_accessor :name
def set_name(your_name)
name = your_name
end
end
m = Person.new
p m.name
m.set_name('today')
p m.name # => ²ÂÊÇʲô
Èç¹ûÄã²ÂÊÇtoday¾Í´ó´íÌØ´íÁË£¬´ð°¸ÊÇnil£¬ÎªÊ²Ã´ÊÇnilÄØ£¬ÔÚµÚ5ÐУ¬ÎÒÃ÷Ã÷µ÷ÓõÄÊÇattr_accessorÉú³ÉµÄname=·½·¨¸³ÖµµÄ°¡£¬Äã¿ÉÒÔÔÚÇ°Ãæ¼ÓÉÏselfÊÔÊÔ£¬´úÂëÈçÄãÔ¤ÆÚµÄÒ»ÑùÖ´ÐÐÁË¡£ÔÚÕâÖÖÇé¿öÏÂname = your_name²¢Ã»ÓÐÈ¥µ÷ÓÃattr_accessorÉú³ÉµÄxx=·½·¨£¬¶øÊǽ«nameµ±×÷ÁËÒ»¸ö¾Ö²¿±äÁ¿£¬Èç¹ûÏÔʽµÄÖ¸¶¨self£¬¾ÍûÓÐÎÊÌâÁ
Ïà¹ØÎĵµ£º
#Ò»¡¢¶¨ÒåÒ»¸öÀà
class Person
def initialize(name,age=18)
@name=name;
@age=age;
@motherland="china";
end
def talk
puts "my name is "+@name+" and I am "+@age.to_s
&nb ......
When I try the command "gem install thrift" with Ruby 1.9.1, I got a compilation error with something related to a C function "strlcpy()".
Then I searched the web. It seems I am not alone and the community know it.
However I do not want to wait for official update, I want to ......
rubygems
Ruby on Rails ÊÇÒ»¸ö¿ÉÒÔʹÄ㿪·¢£¬²¿Êð£¬Î¬»¤ web Ó¦ÓóÌÐò±äµÃ¼òµ¥µÄ¿ò¼Ü¡£
¡¡¡¡RubyµÄ×÷ÕßÓÚ1993Äê2ÔÂ24ÈÕ¿ªÊ¼±àдRuby£¬Ö±ÖÁ1995Äê12Ô²ÅÕýʽ¹«¿ª·¢²¼ÓÚfj£¨ÐÂÎÅ×飩¡£Ö®ËùÒÔ³ÆÎªRuby£¬ÊÇÒòΪPerlµÄ·¢ÒôÓë6Ôµĵ®Éúʯpearl£¨ÕäÖ飩Ïàͬ£¬Òò´ËRubyÒÔ7Ôµĵ®Éúʯruby£¨ºì±¦Ê¯£©ÃüÃû¡£railsÔÚÓ¢ÎÄÖÐÊÇÀ¸¸ËµÄ ......
ת Adding Sound to Your Ruby Apps
Have you ever thought about including sounds in your Ruby application? Used sparingly, sound may enhance your applications by adding audio cues or a custom touch. You could, for example, play a beep or chime that announces the completion of a lengthy process. Per ......