`

重新学习Programming Ruby 2nd,读书笔记,不断增加

    博客分类:
  • Ruby
阅读更多
ruby 代码

1。使用h=hash.new(0)可以把hash中的每一个元素都初始化为0

2。类的实例变量能够在类内部任意位置定义(@xxx),而且可以被类内方法访问。A class variable is shared among all objects of a class, and it is also accessible to Class variables are private to a class and its instances. If you want to make them accessible to the outside world, you’ll need to write an accessor method the class methods that we’ll describe later.

3。$: ruby的环境变量查询路径

4。class << 表示向类中添加方法,例如:

ruby 代码
 
  1. class A   
  2.  class << self  
  3.   def its_nothing_happned   
  4.   end  
  5.  end  
  6. end  

 调用A.methods可以看到A中有了名为its_nothing_happned这个类方法

5。ruby中的private方法和Java、C#中的方法不同!见代码:
 #ruby代码

ruby 代码
 
  1. class A   
  2.  private   
  3.  attr_access :nth  
  4.   
  5.  #注意,这个方法是错的!   
  6.  def compare(class_a_obj)   
  7.   if @nth == class_a_obj.nth #不可以访问另外一个A的私有字段!!   
  8.    true  
  9.   else  
  10.    false  
  11.   end  
  12.  end  
  13. end  

 但是java和C#都可以访问:
 

c# 代码
 
  1. class Test   
  2.  {   
  3.   private string name;   
  4.   public Test(string name)   
  5.   {   
  6.       this.name = name;   
  7.   }   
  8.   
  9.   public override bool Equals(object obj)   
  10.   {   
  11.       if (this.name == ((Test)obj).name)   
  12.       {   
  13.       return true;   
  14.       }   
  15.       return false;   
  16.   }   
  17.  }   

    

java 代码
 
  1. class Test   
  2. {   
  3.  private String name;   
  4.     
  5.  public Test(String name)   
  6.  {   
  7.   this.name = name;   
  8.  }   
  9.     
  10.  public boolean equal(Test t)   
  11.  {   
  12.   if(this.name == t.name)   
  13.   {   
  14.       return true;   
  15.   }   
  16.   return false;   
  17.  }   
  18. }   


 

6。类可以在类内部访问此类所有实例的protected类型变量:

ruby 代码
 
  1. class Account  
  2.   attr_reader :balance       # accessor method 'balance'  
  3.   protected :balance         # and make it protected  
  4.   def greater_balance_than(other)  
  5.     return @balance > other.balance  
  6.   end  
  7. end  

7。A variable is simply a reference to an object,variable is not a object.

8。ruby虽然每个元素都是object,包括int,float等,但是这些基本类型处理起来似乎和C#有几分相似,例如:
ruby 代码
 
  1. s1 = "Jim"  
  2. s2 = s1  
  3. s2[0] = "T"  
  4. puts s1 #Tim  
  5. puts s2 #Tim  
这个例子上看应该是正确的,因为s1是指向真正字符串的指针,此时字符串保留在堆上,s2同样是个指针指堆上的字符串,所以修改s2会同时影响到s1,但是,让我们来看“数值类型”是什么表现:
ruby 代码
  1. a = 1  
  2. b = a  
  3. b = 2  
  4. puts a  #1

9。数组中可以用array[-1]来代替数组的最后一个元素,用array[1,-1]来代表数组中第一个到最后一个元素。

10。注意这段程序,关于block中使用block外定义的变量问题:
ruby 代码
 
  1. a = [1, 2]  
  2. b = 'cat'  
  3. a.each {|b| c = b * a[1] }  
  4. a   #[1, 2]  
  5. b    2  
  6. defined?(c) nil  

再看这段:
ruby 代码
 
  1. arr = []  
  2. def nth  
  3.   yield  
  4. end  
  5.   
  6. nth { arr = %w{1 2 3 4 5 6} }  
  7. p arr  #["1""2""3""4""5""6"]  


其中的问题在于block里面使用了于外面定义同名的变量,而且使用外部变量在block前,不过在ruby2.0中会改变这个block中变量继承外部变量的方式。

11。用?xxx的方式获得xxx对应的int值,这里xxx是一个ASCII字符,例如?a, ?C-M-a(Ctrl+Alt+a)

12。在判断语句中使用range

ruby 代码
 
  1. strs = []   
  2. strs << "hello"  
  3. strs << "start"  
  4. strs << "haha"  
  5. strs << "end"  
  6.   
  7. strs.each do |str|   
  8.   puts str if str=~/start/..str=~/end/   
  9. end  

输出为:
start
haha
end

13。If you define a method inside another method, 1.8 the inner method gets defined when the outer method executes.

14。ruby赋值的方式可谓多种多样,如下:

ruby 代码
 
  1. arr = [1,2,3,[4,5,6]]   
  2. a,b,c,d = arr   
  3. p a #1   
  4. p b #2   
  5. p c #3   
  6. p d #[4,5,6]  

给数组赋值:

ruby 代码
 
  1. arr = []   
  2. arr = 1,2,3,[4,5,6]   
  3. p arr #[1, 2, 3, [4, 5, 6]]  

 15。ruby1.8中virtual viarable的赋值方法返回值发生了变化:

ruby 代码
 
  1. class A   
  2.   def name=(value)   
  3.     @name = value   
  4.     return 99   
  5.   end  
  6.   def name   
  7.     return @name  
  8.   end  
  9. end  
  10.   
  11. a = A.new  
  12. p a.name = 20 #20  

可以看到,使用赋值方法返回的值一定是传入参数的值,而跟在赋值方法中指定的返回值无关。但是在ruby1.8之前的版本,赋值之后返回的值是赋值方法最后一条执行语句的返回值。

16。注意并行赋值的一点儿细节(注意b、c和y的值):

ruby 代码
 
  1. x = 0   
  2. a, b, c = x, (x += 1), (x += 1)   
  3. y = 0   
  4. y,y,y = x,(x+=1),x+=1   
  5. p a #0   
  6. p b #1   
  7. p c #2   
  8. p x #4   
  9. p y #4  

17。参数前缀的意义,&表示将这个参数看作一个pro,*表示将此参数包装成一个数组:

ruby 代码
 
  1. p1 = 2   
  2. p2 = {:name=>"jack"}   
  3. p3 = [3,4]   
  4. a,b = p1,p2   
  5. p a   
  6. p b   
  7. a,*b = p1,p3   
  8. p a   
  9. p b   
  10. a,b=p1,*p2   
  11. p a   
  12. p b  

结果:

2
{:name=>"jack"}
2
[[3, 4]]
2
[:name, "jack"]

18。并行赋值的tips:Nested Assignments Parallel assignments have one more feature worth mentioning. The left side of an assignment may contain a parenthesized list of terms. Ruby treats these terms as if they Prepared exclusively for Yeganefar CONDITIONAL EXECUTION 87 were a nested assignment statement. It extracts the corresponding rvalue, assigning it to the parenthesized terms, before continuing with the higher-level assignment.
b, (c, d), e = 1,2,3,4 ! b == 1, c == 2, d == nil, e == 3

ruby 代码
 
  1. b, (c, d), e = [1,2,3,4] ! b == 1, c == 2, d == nil, e == 3   
  2. b, (c, d), e = 1,[2,3],4 ! b == 1, c == 2, d == 3, e == 4   
  3. b, (c, d), e = 1,[2,3,4],5 ! b == 1, c == 2, d == 3, e == 5   
  4. b, (c,*d), e = 1,[2,3,4],5 ! b == 1, c == 2, d == [3, 4], e == 5  

19。在正则表达式中,$~用来储存MatchData,其中有关于MatchData的详细信息。同时$1~$9也用来储存多匹配时的多个MatchData。

20。正则表达式:[]的开始加上^表示negative,例如"bcd"=~/[^aeiou]/ =>b

21。
r{m,n}  matches at least “m” and at most “n” occurrences of r.
r{m,}  matches at least “m” occurrences of r.
r{m}  matches exactly “m” occurrences of r.


22。在重复符号后面加 ? 取消贪婪性
show_regexp(a, /\s.*?\s/) =>   The<< moon >>is made of cheese

23。
Parentheses also collect the results of pattern matching. Ruby counts opening parenthe-
ses, and for each stores the result of the partial match between it and the corresponding
closing parenthesis. You can use this partial match both within the rest of the pattern
and in your Ruby program. Within the pattern, the sequence \1 refers to the match of
the first group, \2 the second group, and so on. Outside the pattern, the special variables
$1, $2, and so on, serve the same purpose.
     "12:50am" =~ /(\d\d):(\d\d)(..)/      =>  0
     "Hour is #$1, minute #$2"                =>  "Hour is 12, minute 50"
     "12:50am" =~ /((\d\d):(\d\d))(..)/    =>  0
     "Time is #$1"                             =>  "Time is 12:50"
     "Hour is #$2, minute #$3"                =>  "Hour is 12, minute 50"
     "AM/PM is #$4"                           =>"AM/PM is am"


24。在我们定义一个方法的时候,如果在最后一个形参前面加上*,则表示传入的实参多余形参个数的时候,多余的实参会被包装成一个数组,例如:
def meth(*a)
  if a.is_a?Array
    puts a.join(' ')
  else
    puts a
  end
end
meth(1) => 1
meth(1,2,3,4,5) => 1 2 3 4 5
与上面对应的,在我们传入参数的时候,如果在属性类型的实参前面加上*,则表示将会把数组中的元素释放出来,数组中的每一个元素都会被当作一个实参对待,例如:
def meth(a,b,c)
  puts "#{a} #{b} #{c}"
end
meth(*[1,2,3]) => 1 2 3


25。在对方法传参的时候,假如传入的参数列表中最后几项都是hash的key=>value形式,那么ruby会自动把这些key=>value包装到一个hash表中作为一个实参,例如:
def meth(a,b)
  p a
  p b
end
meth("L.A",:name=>"jack",:age=>46,:sex=>'male')
=>"L.A"
=>{:name=>"jack",:age=>46,:sex=>"male"}
=>nil
需要注意的是这些key value对必须出现在实参列表的最后,以上面的程序为例子,假如我们改变输入顺序:
meth(:name=>"jack",:age=>46,:sex=>'male',"L.A")
ruby的编译器会出错



分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics