ruby tips

变量名

$ 全局变量 @ 实例变量 @@ 类变量 ^A 类名首字母大写

'a'.ord 97.chr

比较 = equal?

str1 = 'string' str2 = 'string' str1.object_id #=>84640 str2.object_id #=>84620 str1 == str2 #=>true str1.equal?(str2) #=>false 1 == 1.0 #=>true

class

'string'.class 1.class 1.object_id 1.methods Fixnum.ancestors Fixnum.instance_methods 1.kind_od? Fixnum Fixnum.kind_of? Class

each

(1..100).each do |i|

puts i

end (1...100).each do |i|

puts i

end 3.times do

put 'hello'

end 1.upto(100) do |i|

puts i

end 1.upto 100 do |i|

puts i

end

%w[ days months minutes seconds ].each do |name|

puts name

end

hash = { 'baxter'=>'stephen','benford'=>'charles'} hash.each do |key,values|

puts "#{values} #{key}"

end

'hello world'.each_byte do |i|

puts i

end #=> ascii 数字

'hello world'.each_char do |i|

puts i

end #=> char

strs.each_line do |i|

puts i

end

<<

1 << 2 #=>4 ['a', 'b'] << 'c' #=>['a', 'b', 'c'] a, b = 'hello', 'world'

class Foo < Object end class Fuc < (user_input == "1" ? bar : baz ) end

debug

ruby -rdebug hello.rb

time

Time.now Time::now

array

a = [ 'ruby' , 'python' , 'prel' ] a[0..2] a[0...2] a[0,2] a[4,2] a.include? 'ruby' a *= 2 a.sort a.uniq a.uniq! a.each_with_index do |item,index|

puts [ item , index ]

end a,b,*c,d = 1,2,3,4,5 #=>a=1 b=2 c=[3,4] d=5

函数式

a.map{|item| item[1]} a.sort { |x,y| x.to_i <=> y.to_i } a.select { |i| i.include? 'a' } a.reject { |i| i.include? 'a' } a.inject(0) {|sum,i| sum+i}

哈希表

month = {

'Jan'=>1 , 'Feb'=>2 , 'Mar'=>3 , 'Apr'=>4 , 'May'=>5

} month['Feb'] month = { Jan:1 , Feb:2 , Mar:3 , Apr:4 , May:5 } month.fetch :Jan #=>不在范围内的访问出错 month.key? :Jan

month.each do |en,num|

puts "#{en} #{num}"

end

month.map { |en,num| "#{en} is #{num}" }

month.map.with_index { |(en,num),i| "#{i}. #{en} is #{num}" }

数字

100000000000000000000000000000000000000000000000 100_000_000 2.11e10

0x92E #16 0127 #8 0b10011 #2

0x 0X 16
0o 0O 0 10
0d 0D 无 8
0b 0B 2

1.infinite? 1.finite? 1.nan?

-1.divmod(2) #=>[-4,1] -3.14.abs 0.5772.ceil @=>1 大于等于的最小整数 a ||= 0

1.odd?

输入输出

puts 'ddd' printf("%.2d\n",23.1023) $stderr STDERR $stdout STDOUT $stdin STDIN $1 $: 读入文件库时的搜索路径 RUBY_VERSION gets.chop ARGV.join('+') ARGF

File.open('filename') { |f|

puts f.read

} File.open('filename') do |f|

puts f.read

end File.open('filename','r:URF-16BE') { |f|

puts f.read.encoding

}

r 只读 不存在则错误
W 只写 总是新建
I+ 读写 不存在则错误
a 追加 末尾 不存在则新建
a+ 读写 末尾 不存在则新建
b 二进制  

RDONLY 只读
WRONLY  
rDWR  
APPEND  
CREAT  
EXCL  
NONBLOCK  
TRUNC  
NONCTTY  
BINARY  
SYNC  

File.open('a.txt','r+b') { |f|

f.pos f.read(3) f.pos f.gets f.seek(-1,File::SEEK_END) f.getc f.readchar #与getc相同,只是不存在时会发生错误

}

SEEK_SET 开头
SEEK_CUR 当前
SEEK_END 结尾

require 'stringio' buf = String.new sio = StringIO.new(buf) $stderr = #stdout = sio warn 'wrong' $stdout = STDOUT puts buf

类型转化

.to_i .to_s .to_f

Math

Math.acos(x) Math.log(x) Math::sqrt(x) Math::E Math::PI

String

str = String.new str << "hello" << ' ' << "world" << 75 str.upcase str.encoding str.bytesize

'string'.size 'string'.length 相同 语法糖

shell `

ls = ls dat = date

Encoding

Encoding.name_list Encoding.find('CP1258')

  1. -- coding:utf-8 --

str.force_encoding('CP1258')

百分号记法

%!hoge! 字符串 转义符 公式有效
%q!hoge! 字符串 转义符 公式无效
%Q!hoge! 字符串 转义符 公式有效
%x!hoge! 与反引号相同 公式有效
%r!hoge! 正则表达式
%w!hoge! 字符串数组 用空格隔开
%W!hoge! 同上 转义符 公式有效
%s!hoge! Symbol 字面量

[ ] ( ) count = database_connector.get_int(<<"EOS" % author.id)

SELECT COUNT(*) FROM BOOK WHERE BOOK.AUTHOR_ID = %D

EOS if something?

database_connector.search <<-"SQL" Select * FROM BOOK WHERE expired_at <= CURRENT_DATA SQL

end

注释

=begin ... end

#

正则表达式

if /<a href="(.*?)"[>]>/ =~ str

puts 'find' + $1

end str = str.gsub(/solomon grundy/,'hippopotamus') str = str.gsub(/solomon grundy/) {"#{$1}."}

str.scan

内置变量

$stderr STDERR $stdout STDOUT $stdin STDIN $1 $: 读入文件库时的搜索路径 RUBY_VERSION _FILE_ 当前执行的源文件名称 _LINE_ 当前指定的 _ENCODING_ 当前文件编码

gets.chop ARGV.join('+') ARGF

条件

var = a ? b : c

if condition1 then

do_something1

elsif condition2 then

do_something2

else

do_something3

end do_something if condition

unless condition

puts 'condition is false'

end do_something unless condition

case value when 1 then

do_something1

when 2,3 then

do_something2

when [4,5]

do_something3

when 6..10

not_execute

else

do_something4

end

puts (1..9) === 2

begin

do_something

rescue ArgumentError => error then

puts error.message

rescue TypeError

do_something2

ensure

puts 'ensure part'

end

catch(:exit) {

loop do loop do throw :exit end end

}

def some_method(a=0)

return a,1,2,3

end

proc = Proc.new { puts 'ddd' }

attr_reader attr_writer attr_accessor