欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Ruby Trick RubyrubygemsCC++C# 

程序员文章站 2024-03-20 17:06:46
...
很喜欢http://www.rubyinside.com这个网站,里面记载了一些Ruby相关的新闻,以及技术相关的,这里爬几个可能会用到的Ruby Trick.

1. 分解枚举

a = %w{a b}
b = %w{c d}
[a + b]                              # => [["a", "b", "c", "d"]]
[*a + b]                             # => ["a", "b", "c", "d"]
a = { :name => "Fred", :age => 93 }
[a]                                  # => [{:name => "Fred", :age =>93}]
[*a]                                 # => [[:name, "Fred"], [:age, 93]]
a = %w{a b c d e f g h}
b = [0, 5, 6]
a.values_at(*b).inspect              # => ["a", "f", "g"]

2. 不用String 或是 Symbol做hash的键

does = is = { true => 'Yes', false => 'No' }
does[10 == 50]                       # => "No"
is[10 > 5]                           # => "Yes"

3.快速赋值

a, b, c, d = 1, 2, 3, 4

def my_method(*args)
  a, b, c, d = args
end

def initialize(args)
  args.keys.each { |name| instance_variable_set "@" + name.to_s, args[name] }
end

4. 使用Range

# if x > 1000 && x < 2000
year = 1972
puts  case year
        when 1970..1979: "Seventies"
        when 1980..1989: "Eighties"
        when 1990..1999: "Nineties"
      end

5. DRY很彻底

%w{rubygems daemons eventmachine}.each { |x| require x }

6. 使用三目运算符(有一天我居然听说一个我的同事工作了六七年,说没用用过这个操作符,天啊,什么世道?什么公司敢用这样的程序员? 和这样的工作,很危险)

def is_odd(x)
  # Wayyyy too long..
  if x % 2 == 0
    return false
  else
    return true
  end
end

=>

def is_odd(x)
  x % 2 == 0 ? false : true
end

==》

def is_odd(x)
  # Use the logical results provided to you by Ruby already..
  x % 2 != 0
end

7. 写程序要捕捉异常

def do_division_by_zero
   5 / 0
end

begin
  do_division_by_zero
rescue => exception
  puts exception.backtrace
end

8. 确保有东西可迭代

items = "hello"
[*items].each do |item|
  # ...
end

9 捕获异常不一定非要有begin

def x
  begin
    # ...
  rescue
    # ...
  end
end

=>

def x
  # ...
rescue
  # ...
end

10. 块注释

puts "x"
=begin
  this is a block comment
  You can put anything you like here!

  puts "y"
=end
puts "z"

11 rescue to the rescue

h = { :age => 10 }
h[:name].downcase                         # ERROR
h[:name].downcase rescue "No name"        # => "No name"