`
lionheart
  • 浏览: 91233 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Ruby way --- 符号和范围类

阅读更多

1.用符号定义类的属性:

 

sym = :@property_name
instance_variable_set(sym, "property_value")
instance_variable_get(sym)  # property_value

 

2. 使用方法 to_str/to_s 和 to_sym 在字符串和符号之间进行替换:

 

a = "value"
b = :value
a == b.to_s #true
b == a.to_sym #tru

 

3. 符号的一种巧妙用法:

 

#在Symbol类中定义如下方法:
def to_proc
      proc {|obj, *args| obj.send(self, *args)}
end

result = array_instance.map(&:capitalize)
 

 

4. 开范围和闭范围:

 

1..3.to_a # [1,2,3] 
1...3.to_a # [1,2]

 

5. 查找范围的起点和终点:

    begin和first方法返回起点;end和last方法返回终点。

 

 r = 1..5

r.first == 1
r.begin == 1
r.end == 5
r.last == 5

 

6. exclusive_end? 指出范围是否包含终点。

 

7. 对范围进行迭代,要求范围中的元素定义了有意义的 succ 方法。

String类定义了succ方法,但是它的后继可能不是我们所期望的。比如:

 r = "2".."10"

r.each {|x| puts x} # output nothing.

因为按字符串的比较方式,起点"2"要大于终点"10"。

浮点数没有succ方法,因此不能对浮点数范围进行迭代。

 

8. include? / memeber? 判断指定元素是否在范围内。

 

9. 范围转换为数组的方法: to_a。 这个方法是通过不断调用 succ 方法实现的。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics