Ruby Tricks 大全

下面所有用法都是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 = args
end 


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]
=> nil
irb(main):076:0> a.fetch(8)
IndexError: index 8 out of array
        from (irb):76:in `fetch'
        from (irb):76
        from :0
irb(main):077:0> a.fetch(8,nil)
=> nil
irb(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_o
f? String}
=> {}
irb(main):009:0> hash[1]
=> nil
irb(main):010:0> hash["key"]
=> "KEY"



Regex也可以有默认返回值:

 email = "Fred Bloggs <fred@bloggs.com>"
email.match(/<(.*?)>/)[1]            # => "fred@bloggs.com"
email[/<(.*?)>/, 1]                  # => "fred@bloggs.com"
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 <  2
end
puts queue.inspect

# Output:
#   Added to queue
#   Added to queue
#   ["hello", "world"]



三元操作符:

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

 

 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 = 1972
puts  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; end
begin
  do_division_by_zero
rescue => exception
  puts exception.backtrace
end



9.Rescue blocks don't need to be tied to a 'begin'

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

 

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


10.Rescue to the rescue

 h = { :age => 10 }
h[:name].downcase                         # ERROR
h[: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!
end

class C
  include M

  def fun
    not!
  end
end

M.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!'
  end
end


class C
  include M

  def fun
    not! + ' ' + yea!
  end
end
M.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)
  end
end
class RandomSubclass < [Array, Hash, String, Fixnum, Float, TrueClass].rand

end

RandomSubclass.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'
  end
end

a = A.new
a.my_private_method # Raises exception saying private method was called
a.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__
line1
line2
line3


17.FX和NS两位大神提供...目前不知道是做什么的.......

gets gets

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
智慧校园建设方案旨在通过融合先进技术,如物联网、大数据、人工智能等,实现校园的智能化管理与服务。政策的推动和技术的成熟为智慧校园的发展提供了基础。该方案强调了数据的重要性,提出通过数据的整合、开放和共享,构建产学研资用联动的服务体系,以促进校园的精细化治理。 智慧校园的核心建设任务包括数据标准体系和应用标准体系的建设,以及信息化安全与等级保护的实施。方案提出了一站式服务大厅和移动校园的概念,通过整合校内外资源,实现资源共享平台和产教融合就业平台的建设。此外,校园大脑的构建是实现智慧校园的关键,它涉及到数据中心化、数据资产化和数据业务化,以数据驱动业务自动化和智能化。 技术应用方面,方案提出了物联网平台、5G网络、人工智能平台等新技术的融合应用,以打造多场景融合的智慧校园大脑。这包括智慧教室、智慧实验室、智慧图书馆、智慧党建等多领域的智能化应用,旨在提升教学、科研、管理和服务的效率和质量。 在实施层面,智慧校园建设需要统筹规划和分步实施,确保项目的可行性和有效性。方案提出了主题梳理、场景梳理和数据梳理的方法,以及现有技术支持和项目分级的考虑,以指导智慧校园的建设。 最后,智慧校园建设的成功依赖于开放、协同和融合的组织建设。通过战略咨询、分步实施、生态建设和短板补充,可以构建符合学校特色的生态链,实现智慧校园的长远发展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值