• 最近刚学习到这个,举个例子是

    [11] pry(main)> [1,2,{a: "1", b: "s"},{c:"3"}].extract_options!
    => {:c=>"3"}
    

    上面有人提到的是:

    数组最后一项是不是 Hash,如果是的话就提取出来了

    源代码的话:

    class Array
      # Extracts options from a set of arguments. Removes and returns the last
      # element in the array if it's a hash, otherwise returns a blank hash.
      #
      #   def options(*args)
      #     args.extract_options!
      #   end
      #
      #   options(1, 2)        # => {}
      #   options(1, 2, a: :b) # => {:a=>:b}
      def extract_options!
        if last.is_a?(Hash) && last.extractable_options?
          pop
        else
          {}
        end
      end
    end
    
  • 学习了!

  • 👍 👍

  • 使用 ClassName.class_eval 可以定义一个实例方法。

    这句话说得不完全,是可以定义一个实例方法,也可以定义类方法,类变量等等等.... 用 class_eval 相当于在重新打开了这个类,然后写代码。

    一开始看这里感觉只能定义实例方法一样

  • 爬虫的话,mechanize 也不错 https://github.com/sparklemotion/mechanize

  • 我的理解: URL 资源发出 HTTP 请求-> nginx -> passenger-> rack ->rails

    当我们在输入一个 URL 的时候,浏览器向服务器发送 HTTP 请求,中间会经过 web server(nginx),然后经过经过 nginx 的时候,会经过 passenger(application server),之后会经过 rack(处理 http 请求和 rails app 的接口),再到 rails app 的核心里面,routes,controller,model,view 这样的一个过程。

  • Ruby 对 csv 文件进行统计 at August 03, 2018
    require 'csv'
    
    emergency = 0
    normal = 0
    important = 0
    
    CSV.foreach('123.csv', headers: true) do |row|
      if row[3] == '重要'
        important += 1
      elsif row[3] == '普通'
        normal += 1
      elsif row[3] == '紧急'
        emergency += 1
      end
    end
    
    puts "重要:#{important}"
    puts "普通:#{normal}"
    puts "紧急:#{emergency}"
    

    写法可能很累赘,其实不用 if-elsif-elsif ,改用

    case
      when
      when
      when
    end
    

    或许更好