Ruby Tricks 大全
编程技术  /  houtizong 发布于 3年前   90
下面所有用法都是1.8.6里的,同时欢迎补充1.9和rails里面的tricks...
一.神奇的*
1.String#*
"Hello!" * 2 #=> "Hello!Hello!"
2.Array#*
%w{one two three} * 2 #=> ["one", "two", "three", "one", "two", "three"]
3.Shortcut for Array#join
%w{one two three} * ", " #=> "one, two, three"
%w{this is a test} * ", " # => "this, is, a, test" h = { :name => "Fred", :age => 77 } h.map { |i| i * "=" } * "&" # => "age=77&name=Fred"
4.explore to enumerator
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"]
fruit = ["apple","red","banana","yellow"]#=> ["apple", "red", "banana", "yellow"]Hash[*fruit] #=> {"apple"=>"red", "banana"=>"yellow"}
5.*arg作为参数
def my_method(*args) a, b, c, d = argsend
6.Object#*
match, text, number = *"Something 981".match(/([A-z]*) ([0-9]*)/)
a, b, c = *('A'..'Z')Job = Struct.new(:name, :occupation)tom = Job.new("Tom", "Developer")name, occupation = *tom
二.默认返回值.
Array#[]在index超出array范围时会默认返回nil(如果不想要默认值或是要扩展默认值可以用Array#fetch):
irb(main):074:0> a = [1 ,2, 3]=> [1, 2, 3]irb(main):075:0> a[5]=> nilirb(main):076:0> a.fetch(8)IndexError: index 8 out of array from (irb):76:in `fetch' from (irb):76 from :0irb(main):077:0> a.fetch(8,nil)=> nilirb(main):078:0> a.fetch(8,"index out of array!")=> "index out of array!"
Hash也是在key不存在的时候返回默认值nil,也可以自己设置默认值或default_proc
irb(main):008:0> hash = Hash.new{|hash,key| hash[key] = key.upcase if key.kind_of? String}=> {}irb(main):009:0> hash[1]=> nilirb(main):010:0> hash["key"]=> "KEY"
Regex也可以有默认返回值:
email = "Fred Bloggs <[email protected]>"email.match(/<(.*?)>/)[1] # => "[email protected]"email[/<(.*?)>/, 1] # => "[email protected]"email.match(/(x)/)[1] # => NoMethodError email[/(x)/, 1] # => nil
当然最强大的还是method_missing了....
三.习以为常的single line method
在ruby里一行代码完成一个方法是很常见的....这主要归功于enumerable模块里面定义的神奇方法,还有if,unless等
queue = []%w{hello x world}.each do |word| queue << word and puts "Added to queue" unless word.length < 2endputs queue.inspect# Output:# Added to queue# Added to queue# ["hello", "world"]
三元操作符:
def is_odd(x) x % 2 == 0 ? false : trueend
all?, any?, collect, detect, each_cons, each_slice, each_with_index, entries, enum_cons, enum_slice, enum_with_index, find, find_all, grep, include?, inject, inject, map, max, member?, min, partition, reject, select, sort, sort_by, to_a, to_set, zip
p queue = %w{hello x world}.select { |word| word.length >= 2 }
四.其他
1.Format decimal amounts quickly
money = 9.5"%.2f" % money # => "9.50"
2.Surround text quickly
"[%s]" % "same old drag" # => "[same old drag]"
3.Delete trees of files
require 'fileutils'FileUtils.rm_r 'somedir'
4.Cut down on local variable definitions
(z ||= []) << 'test'
5.Using non-strings or symbols as hash keys
does = is = { true => 'Yes', false => 'No' }does[10 == 50] # => "No"is[10 > 5] # => "Yes"
6.Do something only if the code is being implicitly run, not required
if __FILE__ == $0 # Do something.. run tests, call a method, etc. We're direct.end
7.Use ranges instead of complex comparisons for numbers
#让 if x > 1000 && x < 2000 歇菜吧 year = 1972puts case year when 1970..1979: "70后" when 1980..1989: "80后" when 1990..1999: "90后" end
8.See the whole of an exception's backtrace
def do_division_by_zero; 5 / 0; endbegin do_division_by_zerorescue => exception puts exception.backtraceend
9.Rescue blocks don't need to be tied to a 'begin'
def x begin # ... rescue # ... endend
def x # ...rescue # ...end
10.Rescue to the rescue
h = { :age => 10 }h[:name].downcase # ERRORh[:name].downcase rescue "No name" # => "No name"
11.convert a Fixnum into any base up to 36
>> 1234567890.to_s(2)=> "1001001100101100000001011010010">> 1234567890.to_s(8)=> "11145401322">> 1234567890.to_s(16)=> "499602d2">> 1234567890.to_s(24)=> "6b1230i">> 1234567890.to_s(36)=> "kf12oi"
12.module_function
#让module更class module M def not! 'not!' end module_function :not!endclass C include M def fun not! endendM.not! # => 'not!C.new.fun # => 'not!'C.new.not! # => NoMethodError: private method `not!' called for #<C:0x1261a00>
module M module_function def not! 'not!' end def yea! 'yea!' endendclass C include M def fun not! + ' ' + yea! endendM.not! # => 'not!'M.yea! # => 'yea!'C.new.fun # => 'not! yea!'
13.use here document and any character you want to delimit strings
message = "My message"contrived_example = "<div id=\"contrived\">#{message}</div>"contrived_example = %{<div id="contrived-example">#{message}</div>}contrived_example = %[<div id="contrived-example">#{message}</div>]sql = %{ SELECT strings FROM complicated_table WHERE complicated_condition = '1'}sql = <<-SQL SELECT strings FROM complicated_table WHERE complicated_condition = '1'SQL
14.define_method
((0..9).each do |n| define_method "press_#{n}" do @number = @number.to_i * 10 + n end end
15.create Class at run time..
class Array#define Array#rand def rand self.fetch Kernel.rand(self.size) endend
class RandomSubclass < [Array, Hash, String, Fixnum, Float, TrueClass].randendRandomSubclass.superclass # could output one of 6 different classes.
16.call private methods of class with send.
class A private def my_private_method puts 'private method called' endenda = A.newa.my_private_method # Raises exception saying private method was calleda.send :my_private_method # Calls my_private_method and prints private method called'
16.__END__
p DATA #=>#<File:tt.rb>p DATA.read #=> "line1\nline2\nline3"__END__line1line2line3
17.FX和NS两位大神提供...目前不知道是做什么的.......
gets gets
请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!
技术博客集 - 网站简介:
前后端技术:
后端基于Hyperf2.1框架开发,前端使用Bootstrap可视化布局系统生成
网站主要作用:
1.编程技术分享及讨论交流,内置聊天系统;
2.测试交流框架问题,比如:Hyperf、Laravel、TP、beego;
3.本站数据是基于大数据采集等爬虫技术为基础助力分享知识,如有侵权请发邮件到站长邮箱,站长会尽快处理;
4.站长邮箱:[email protected];
文章归档
文章标签
友情链接