ruby的一些特性汇总

    在Ruby中有很多方法是以?和!号结尾的  “?”被用于标示谓词,即返回Boolean直的方法,如Array.empty?(判断数组中元素是否为空)  “!”出现在方法名尾部的感叹号表明使用该方法是需要多加小心。许多Ruby的核心类都定义了  成对的方法,它们具有同样的名称,只是结尾相差一个“!”,通常情况下,不带感叹号的方法返  调用该方法的一个拷贝,二带感叹号的方法则是一个可变方法,该方法会修改原来的对象,如Array  类中的sort和sort! 

1.
    if !is_u_name?(username)
      @params_erros[:username] = username
      @notice += "username error<br/>"

    end


2. ruby方法调用参数不需要括号;


3. Ruby类常量由大写字母开头,如:

TRANSACTOIN_NAMES = %{imageUpload}



4.类中def self. 为定义类方法

http://biyeah.iteye.com/blog/1284489


5. <<是追加操作符


6. @@开始的变量是类变量,@实例变量



7. http://ningandjiao.iteye.com/blog/1857016
Ruby中,类定义的方法和其他的语句没有任何区别,都是一行一行的执行下去的

8.  在Ruby里,要读取,或是改变对象的属性,唯一的途径是调用对象的方法。

9. cattr_accessor就相当于java的类静态变量, 对所有的类实例共享,attr_accessor的用法相当简单, 就相当于getter和setter。cattr_accessor 是利用类变量,会互相影响,相当于只有一个,是共 用的class_inheritable_accessor 在类创建时继承下来,但再更改就不相互影 响了利用类的实例变量可以实现相互没有任何关系

10. 所以, "a ||= b"的正确展开式应该为: "if a then a else a = b end"

-----------------------------------------------------补充----------------------------------------------------

1. 何检测代码块是否存在,可以通过block_given?方法做到
2. attr_accessor
3. rvm --create --ruby-version ruby-1.9.3@my-gemset
4. Bundler.require(:default, Rails.env) if defined?(Bundler)
5. break if $exit
6. if count.zero?
7. ensure #不管有没有异常,进入该代码块
8. spork 一个给测试框架(RSpec 或 现今 Cucumber)用的 DRb 服务器,每次运行前确保分支出一个乾净的测试状态。 简单的说,预载很多测试环境的结果是大幅降低你的测试启动时间,绝对必须用
9.  Cucumber是一个在敏捷团队十分流行的自动化的功能测试工具,但是其不仅仅是一个测试工具,它能够为我们建立一个易读的,可执行的特性文档
    Scenario:测试场景,一个用户特性的一个关键用例就称之为一个测试场景
   
10.
ruby-1.8.7-head - #gemset created /home/dog/.rvm/gems/ruby-1.8.7-head@group
ruby-1.8.7-head - #generating group wrappers..........

11. rvm gemset install bundle
    bundle install

12 gem list

13.
Nat设置dns
VMware Network Adapter VMnet8
#vi  /etc/resolv.conf

14. ./configure --sbin-path=/usr/sbin/nginx --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --user=nginx --group=nginx --with-http_ssl_module --with-http_realip_module --with-http_addition_module --with-http_sub_module --with-http_dav_module --with-http_flv_module --with-http_mp4_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_random_index_module --with-http_secure_link_module --with-http_stub_status_module --with-http_auth_request_module --with-mail --with-mail_ssl_module --with-file-aio --with-http_spdy_module --with-ipv6 --with-threads --with-stream --with-stream_ssl_module

15.
 module ActiveRecord
  class Base
 
    class << self
      alias :old_connection :connection
      def connection
        self.verify_active_connections!
        old_connection
      end
    end

  end
end

16. if self.respond_to? "after_update_all" respond_to? 是个方法

17. unless即是if not,可以省卻一個key。
18.
  def self.time2int(t)
    Time.parse(t).to_i
  rescue
    0
  end

19.
 Object.send(:remove_const, :A)   删除常量

20.
name_list = ["chareice", "angel"]
name_list.map(&:upcase)

:upcase的to_proc方法实现如下:
class Symbol
  def to_proc
    Proc.new {|obj| obj.send(self) }
  end
end

Symbol#to_proc会返回一个带参数的Proc对象,Proc对象所做的是为使用这个Proc对象的对象发送调用名字为该符号的方法。

21.
$!  最近一次的错误信息  
$@  错误产生的位置  
$_  gets最近读的字符串   
$.  解释器最近读的行数(line number)  
$&  最近一次与正则表达式匹配的字符串  
$~  作为子表达式组的最近一次匹配   
$n  最近匹配的第n个子表达式(和$~[n]一样)   
$=  是否区别大小写的标志   
$/  输入记录分隔符  
$\  输出记录分隔符  
$0  Ruby脚本的文件名  
$*  命令行参数  
$$  解释器进程ID  
$?  最近一次执行的子进程退出状态  

22. Ruby的map!(collect!)直接修改数组
23.
因为obj对象没法响应talk这个消息,如果使用 respond_to? 这个方法,就可以实现判断对象能否响应给定的消息了:
obj = Object.new
if obj.respond_to?("talk")
   obj.talk
else
   puts "Sorry, object can't talk!"
end

24.
next if group.blank?
user_group = user_groups.select{|e| e[:group_id] == group_id}.first
users = cache_get_objects2(id_array, 'user') {|ids| Cache3.cache_users(nil, ids) }
user_id = row.delete('user_id')
url_params = {"sort_by" => sort_by, "type" => type}.select{|k,v| !v.blank?}.map{|e| e.join("=")}.join("&")
self.find_by_sql(["SELECT * FROM global_s WHERE status = 1"]).sort_by{rand}[0..(limit - 1)].map{|e| e.gid}

user_h = {}
users = cache_get_users(user_id_a).map { |u| u && self.new(u) }
user_id_a.each_with_index { |user_id,i|  if users[i] then users[i].user_id = user_id end}
users.each do|u|
    next if u.blank?
       user_h.merge!({u.user_id => u})
end

Hash.create(group_ids, find_by_sql(query_statements.join(" UNION ALL ")).map{|e| e.count})

Object.const_get(self).new

return [] if ![link_id,group_id].all?

class GroupAlertJob < Struct.new(:content, :infos, :emails)

25
action和模板默认对应
路由和action默认对应

26.
posts.each_key{|e| posts[e] = posts[e].sort{|x,y| x[:pos] <=> y[:pos]}.slice(0, max_size)}

27.
symbolize_keys和symbolize_keys!会把所有键转化为符号

28.
<%= yield :layout%>
<!--以下两种写法也可以-->
<!--<%=yield%>-->
<!--<%=@content_for_layout%>-->

29.
link = Link.find_by_link_id(link_id)

30.
ruby -ropenssl -e 'p OpenSSL::Digest::Digest.new("sha256")'

31.
@ditems = send("save_#{ditem_type}")
32.
        params.each do |key, ufile|
          if /^file\d+/ =~ key
            next if !is_image?(ufile)
            files_data[ufile.original_path] = ufile.read
          end
        end

    return nil if ![user_id,image_data].all?

33. console中reload!指令,可以重新加载项目
34. if 空字符串, [], {} 全部返回true
35. Rails.logger.error(caller.join("\n"))#e.e.backtrace
    GCC_LOGGER.error $!
36. s.rpartition
37. find(:first, :conditions=>{:user_id=>user_id}) 得到的字段是string类型 
38. 三目运算注意加括号



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值