andyss 发表于 2013-2-4 19:45:45

ruby in forest(1)

我相信每天坚持写一点,在一点一滴的积累中成长。

    想像若是生活在静寂的山林,清晨,窗外下着细雨,泡一壶茶,安静的观察这世界的一角,有时候生活需要这样的静,这样的安详,这样的平和。我非常的向往这种生活,但生活有许多种,一种梦想中的生活,另一种正在追求的生活,一种是梦幻,一种是现实。但哪个才是最好的,谁又知道呢? 写程序对于我是一种生活,安静也是我的另一个向往。
    但文字却常常可以让两种生活重叠,可以幻想漫步在丛林,沿在湖边,阳光照耀在湖面上,光的灵动,不正是宝石在闪闪发光么?可以静静的品味,这迷人的画面。

String,可谓是再平凡不过的,所以选择String开头。非常的喜欢Ruby这种扩展性能,让String也如此具有魅力。

1. String to Array

    str = "ab,cde,f,g,,"    arr = str.split(',')    p arr                     # ["ab","cde","f","g"]


2. String to Hash
    str = "a is b,b is c,c is d,d is e"    arr = str.split(',')    has = arr.inject({}) do |res,s|      res.merge({s.split(' is ').first => s.split(' is ').first.next})    end

3. String to Class
module_eval/class-eval非常的实用。
      class String      def constantize          unless /\A(?:::)?(\w*(?:::\w*)*)\z/ =~ self            raise NameError, "#{self.inspect} is not a valid constant name!"          end            Object.module_eval("::#{$1}", __FILE__, __LINE__)      end      end      class A      def self.test          p "joey"      end      end      p "A".constantize.test    #"joey"

4. String to Symbol

   "a".to_sym   #:a

5. String to Date/DateTime

    "2008-01-01".to_date,   "2008-01-01".to_datetime

6. String to Integer/Float/BigDecimal

    "1".to_i   "1".to_f   "1".to_d    *      "a" * 3 == "aaa"   +      "a"+ "b" == "ab"   <<      "ab" << "c" == "abc"   <=>    "a" <=> "b"#-1   compare A with B (A<=>B)   if A is big than B return 1if A is less than B return -1   if equal return 0

7. String to Method
理论上说,每写一个类,都会自带一个方法send/__send__,send可以让字符串代替方法来使用

   class A   def self.test       p "foo"   end   end   str = "test"   A.send(str)# foo
页: [1]
查看完整版本: ruby in forest(1)