Ruby 读书

输出:

print 

printf 既定格式输出

puts 自动换行

p 显示对象

sprintf 不规则字符串

pp  需要导入库

putc(字母)

转移字符和单双引号

include Math或者直接Math.方法

变量

注释

单行#

多行#=begin  #=end

控制结构

条件:if、unless、case

if 条件 [then]

   动作 

else

   动作

end

循环:

while 条件 do 

     动作

end

次数.times{动作}

定义方法

def  方法名

  动作

end

引用库

require "库名/文件名"

命令行输入

ARGV 数组

read 需要分配文件大小的存储空间

gets 一行空间

ruby simple_grep.rb  样式  文件名

================================

数组

数组名=[]

数组名[索引]获取对象

数组名[索引]=存放对象

数组没有数据类型的限制可以存放任何对象

数组名.size获取数组大小

数组.each{|变量|动作}进行遍历

杂凑/哈希表

杂凑={key=>value的形式存放}

杂凑[键]=存放对象

杂凑.each{|键的变量,值的变量|动作}

redirect 重定向存放执行结果到文件

=================================

对象

数值对象 Numberic

字符串对象 Sring

正则表达式对象 Regexp

时间对象 

文件对象 File

目录对象

数值、杂凑对象 Array/Hash

变量

局部变量 小写字母或_开始

全局变量 $开始

实例变量 @起始

类变量 @@起始

虚拟变量 true/false/self

常数 全大写

str1.equal?(str2) 判断是不是同一对象

值同不等于对象相同

==/eql? 经过必要的变换/不经过变换 

1.0==1 #=>true 

1.0.eql?(1) #=>false

书写易读性建议

换行和分号、缩进、空白

================================

条件判断

判断结果 true/false

str.empty? 长度等于0为true否则false

nil 也是一种假

逻辑运算

&&、||、!  /and、or、not

if 条件 [then]

   语句1

elsif 条件 [then]

   语句2

end

unless 条件 [then] 不满足条件

  语句

else

   语句

end

case 比较的对象   --类似switch的功能

when 值 [then]

  语句

when 值 [then]

  语句

when 值 [then]

   语句

else

  语句

end

=== 判断值相等

================================

循环

times

次数.times do/{ 动作} /end  两种样式

for

for 变量 in 开始值..结束值 [do]

动作

end

for  变量 in 对象 [do]

  动作

end

while

while 条件 [do]

动作

end

until 否定的判断

until 条件 [do]

动作

end 

each 遍历

对象.each do |变量| 动作 end

对象.each {|对象| 动作}

loop{动作}不停循环 配合break停止

break停止,跳出当前循环

next 直接跳到下一次循环

redo 以相同条件重新进行这一次循环

================================

方法

实例方法

类方法

函数性方法

定义方法

def 方法名(参数1,参数2...)

  动作

end

参数接受预设值 name="king"

def hello (name="king")

puts("hello " name)

end

hello() hello king

hello("long") hello long

return 返回值,return可省略返回最后一个计算值

省略return 的实参时,则会返回nil

================================

类与模块

对象.instance_of?  判断对象是否是类的实例

继承

对象.is_a?(父类) 是否继承与

class 类名大写开头

类定义

end

initalize()  初始化方法

以@开头的为实例变量

attr_reader:name方法 只读

attr_Write:name方法  只写

attr_accessor:name方法

def 类名.方法名 end

class<<类名 def 方法名 end end

class 类名 def self .方法名 end end

类名.方法/类名::方法同义

以::连接类和常数

class 类

  PI="3.14"

end

print  类::PI

扩充类

self.

继承

class 类名 < 父类

  类定义

end

super(父类方法)

限制方法的调用

public 

private 内部使用

protected 内部使用/同一个类

使用方法

public : 方法名

public  没有实参即下面所有方法都是public

initialize 恒为private

==============================

模块 不能该创建实例 不能继承

FileText.exist?("路径") 文件是否存在

FileText.size("路径") 文件大小

Mix-in 将模块混进类里

自定义模块

module 模块名

  定义

end

module_function:hello   #将hello方法以模块函数形式公开

模块函数内应用self,可以取得模块本身

===================================

错误处理

数据错误

系统错误

程序错误

忽略错误并继续执行

恢复到错误发生前的状态

重试

结束程序

begin 

  有可能例外的动作

rescue =>存放例外变量

  例外处理

ensure

  总是执行

end

$! 最后发生的例外

$@ 最后例外发生的位置和信息

class 例外类

message 例外消息

backtrace 例外发生位置 $@等同于$.backtrace

sub()第一个

gsub()全部

scan 只获取不替换

retry  重试

当例外处理的begin~end 范围就是整个飞本身时,可以省略begin很end

捕获指定例外 rescue Errno::ENOENT,Errno::EACCES

自定义例外类要继承StandardError

引发例外

raise 消息

raise 例外类

raise 例外类,消息

raise

chatch 和 throw 

throw :test

catch(:test)

==================================================

数字类

数值  整数  整数/大整数

        浮点数

0123/0d123/0x123/0B110101           进制

?字符                 得到字符的ASCII码

** 幂 5**2     25

divmod/remainder  取整/取余

Infinity 无限大

NaN  非数值

Math 数学模块

数值转换

to_f   转换为Float

to_i  转换Int

返回比接收者大的最小整数ceil方法/比你接收者小的的最大整数floor方法

数数

n.times{|i|...}

form.upto(to){|i|...}  从from书到to累加

from.downto(to){|i|...}  累减

from.step(to,step){|i|...} 从from开始。每次加step,直到to为止

=============================================================

数组

Array.new

Array.new(5)  5个nil

Array.new(5,0)  5个0

元素是字符串且不含空白式用%w 建立数组

to_a() 转换为数组

字符串分隔 split()

获取数组

a[n]

a[n...m]

a[n,len]

数组.values_at(n1,n2...) 抽取想要的元素组成新数组

数组交集 arry1 & arry2

数组并集 arry1 | arry2

数组差集 arry1 - arry2

数组前段末端操作

加入 unshift   push  

取出 shift    pop

读取 first  last

a<<item  和a.push(item) 

a.concat(b)/a+b

!对方法具有破坏性

删除

a.compact 删除 nil 重新组成数组  新建对象

a.compact!  返回对象a

a.delete(x) 删除元素

a.delete_at(x) 删除索引

测试元素,条件为真则删除

a.delete_if{|item|...}  破坏性

a.reject{|item|...}  没有符合删除条件返回nil

a.reject!{|item|...}  破坏性

取出部分并替换

a.slice!(n)

a.slice!(n..m) 

a.slince!(n,len) 

删除重复

a.uniq

a.uniq!破坏性

--存在对应的!破坏性方法

a.clooect{|item|...}

a.map{|item|...}

a.flatten 将 嵌套的元素展开

a.reverse 反转

a.sort

a.sort{|i,j|...}

--

a.fill(value)

a.fill(value,begin)  --从begin开始

a.fill(vlue,begin,len) --begin开始len个

a.fill(value,n..m)

a.sort_by{|i|...}

each_with_index 的到元素和索引

多维数组/矩阵

===============================

String 类

变量="***"

#{} 执行ruby语句

转移字符

%Q 、%q 使单双引号原样输出

嵌入文档

message<<"结束记号"

   可内嵌的字符串

结束标记

字符串长度 lenght / size

empty?检查字符串长度为0?

unpack / pack 数组从二进制转换为数组/数组转换为二进制

指定最后一栏的字数时,可以不用指定数值,而已*指定,意味知道字符串尾端的所有文字

big5 汉字2个字节 utf-8 3个字节

删除换行字符的方法

必须删除一个字符 chop

只删除换行字符 chomp

上面两个具有破坏性方法

while line=gets

   line.chomp!

     处理line内容

end

字符串的查找替换

index("**")左侧开始

rindex("**")右侧开始

inclue?("**")包含

Enumerable 模块

s.strip去除空白

--大小写

s.upcase

s.downcase

s.swapcase

s.capitalize

s.tr 取代替换

以上都有破坏性方法

==============================

杂凑/哈希表

Hash.new

设置值 store 

获取值 fetch

直接取出键值对

取出键 数组方式 keys   迭代方式 each_key{|key|...}

取出值 values   each.key{|val|...}

取出键值对 to_a  each_key{|key,val|...}each_key{|pair|...}

查询杂凑存在键或者值

h.key?(key)

h.has_key?(key)

h.include?(key)

h.member?(key)

h.value?(value)

h.has_value?(value)

length / size 杂凑大小

h.clear  清空杂凑

<=> 比较运算符  < 负值 = 为0  >正值

===============================

正则表达式

Regexp.new("**")

%r(样式)

%r<样式>

%r|样式|

%r!样式!

正则表达式=~字符串

if 正则表达式 =~ 字符串

    成功动作

else

    失败动作

end

...... 任何一个字符

quote  忽略所有转义字符

i 忽略大小写

s、e、u、n 指定字符编码方式

x 忽略空白,并忽略#后面的内容

m 让. 能与换行符号匹配成功

===============================

IO 类

输入 STDIN    $stdin  

输出 STDOUT $stdout  

错误输出 STDERR $stderr

tty?

io = open (文件名,模式)

io = File.open(文件名,模式)

io.close

io.close?

require "open-uri"  通信时管道和Socket

require "stringio"

输入

io.gets(rs)

io.each(rs)

io.readlines(rs)

chomp!删除行尾换行字符

io.eof?读到尽头

io.lineo

io.lineo=(number)

io.getc      读取字节

io.each_byte

io.ungetc(ch)  

io.read(size)

io.write(str)

文件指针

io.pos

io.pose=(position)

io.seek(offset , whence)

IO::SEEK_SET  文件指针移动到offset所指位置

IO::SEEK_CUR  从当前算起想对位置offset处

IO::SEEK_END  从文件尾算起相对位置offset处

io.rewind  文件指针移回文件最前端

lineo 方法返回行号也归0

io.truncate(size)  文件长度分割到实参size指定的位置

缓冲

io.flush  强制输出缓冲区里的数据

io.sync

io.sync=(true/false)  可以要求所有缓冲区的写入直接调用flush

与指令交换数据

IO.popen(command,mode)

IO.open("**",mode)

=============================

File  Dir 类

File.rename("before","after") 重命名

require "fileutils"  --复制和移动到新位置

FileUtils.cp("文件","新路径")

FileUtils.mv("文件","新路径")

File.delete("**")

Dir.pwd

Dir.chdir

Dir.open("**")

dir.read

[dir.close]

.  当前

..  上层

;

Dir.glob  使用万能字符获取目录文件名

建立删除目录

Dir.mkdir("**")

Dir.rmdir("**")

文件与目录的属性

File.stat 获取文件或目录的属性

untitle

untitle

File.utime(atime,mtime,path)

File.chmod(mode,path)

File.chown(onwer,group,path) 更改文件所有者

FileTest 模块

untitle

文件名操作

File.basename(path[,suffix])

File.dirname(path)

File.extname(path)

File.split(path)

File.join(dir,base)

File.expand_path(path[,default_dir])

与文件操作相关的程序库

find模块

Find.find(dir){|path|...}

Find.prune

tempfile 模块管理暂存文件

tempfile.new(basename[,tempdir])

tempfile.close(real)

tempfile.open

tempfile.path  返回暂存文件路径

fileuntils 模块

FileUtils.cp(from,to)

FileUtils.cp_r(from,to)

FileUtils.cp_rf(from,to)

FileUtils.mv(from,to)

FileUtils.rm(path) 删除path

FileUtils.rm_r(path)

FileUtils.rm_rf(path)

FileUtils.compare(from,to) 比较文件相同为true

FileUtils.install(from,to[,option])  文件复制到to

FileUtils.mkdir_p(path)

==============================

Time Date 类

Time Date DateTime

untitle

时间格式

Time#strftime(format)

untitle

本地时间

Time#localtime

t=Time.now

t.utc

t.localtime

Time.parse

require "date"

untitle

to_time

DateTime与Time差异

DateTime类继承Date 基本单位是 日

offset 时差处理

计算不到1天的差异使用Rational对象

Rational(分子,分母)

Date.today

>> << 获取几个月后或前的同一天

Date.parse 

===============================

字符串

string="hello"

string.length    统计字符串长度 5

string.length()

string.size

string.count 'l'  统计字母个数

string.count('l')

string.length.next   6

单引号

puts 'may\nbut dosn\'t'  --may but dosn't

初始化另一种方法

untitle

string.silce(3,5)  截取从0开始

string[3,5] 

string[index].chr  获取单个字符

string.empty? 是否为空

string.include? 'h' 是否包含

str<<'a'+'b'

str<<#{val1}  #{val2}

str<< val1<<' '<<val2

Array#join 在数组每个元素之间插入分隔字符串

data=[1,2,3]

s=' '

data.each{|x| s<<x<<' and a '}

s   "1 and a 2 and a 3 and a "

data.join(' and a')   "1 and a 2 and a 3" 忽略最后的分隔符

data.each_with_index{|x,i| s<<x; s<<"|" if i<data.lenght-1 }  1|2|3

num=5

"this is #{num}"  this is 5

#{文本表达式}

要避免字符串插入,可转义字符或者将字符串转入单引号

here document结构

自定义结束的字符

email=<<END

遇到END即结束

变量带入现有字符串

temp='this is %s'

temp % 'money'   --this is money

ERB模板

require 'erb'

temp=ERB.new %q{chunky <%=food %>}

food='ocean'

temp.result(binding)  --chunky ocean

eval(%{''#(self)''},binding)

l

反转字符串

string.reverse

split 分隔符

?A  --65  获取十进制数据

?\C-a  --1

特殊符号只在双引号、%{}、% Q{}中进行解释

单引号和%q{}不能解释

"this\tis" this is 

'this\tsi' this\tis

字符串和值的相互转化

?a   --97

'a'[0] --97

'yuan'[2]  --97

97.chr --"a"

字符串与符号之间的转化

.to_s  

.id2name

.intern

.intern.object_id

处理字符串中每个字符

'hello'.each_byte{|x| puts “#{x}=#{x.chr}”}

'hello'.scan(/./){|x| puts x}

处理字符串中的每个字

.scan(/\w+([-'.]\w+)/){处理}

.word-count

大小写转换

.upcase/downcase

.swapcase 大写变小写,小写变大写

.capitalize  字符串单元格字母大写

.tr('需要替换','替换文本')

空白

.strip 去除空白

.ljust/rjust/center  去除左右中的空白/添加空白

.gsub("\t","  ")  正则去除

.to_str 是否是字符串

.slice(*,*) 起始/长度 从0开始

.[*,*]  数字/正则

$KCODE='u'

require 'jcode'

==============================================

.to_i [(进制)] 不能转换返回0

.to_f

.hex   --八进制

.oct   --十六进制

Integer('需要转换的')

Float('需要转换的')

.scanf()

.approx()

Float::EPSILON

.to_s

BigDecimal()

BigDecimal().precs --检查数值精度

BigMath 

.sqrt

.round

mathn

rand 

.collect

.inject

.reduce(*)

modes   --数组中重复项

Rational    a/b b>0

mean  --平均值

median --中值 非最大非最小

mean_and_standard_deviation  --平均值和偏移量

.between?(*,*)

sub(*,*)

gsub(*,*)

/^  $/

untitle

=~ 

.match

.join

.split

.inspect

------------------------------

.each

.collect

.empty?

.include?

.first 

.last

.reverse

.size

.keys

.delete

.delete_if

case  *

when *

   *

when *

   *

else

end

if/unless

while/until

yield

lambda

Time.now

.local

.gm

.utc

untitle

Fixnum

Bignum

.to_a  --数组

(*...*) 范围

.to_sys

word_count

paragraph_count

sentence_count

%w{ }

====================================================================

换行  \n    跨行 \

Numeric  

String

Array

Hash

Regexp

File

true/false/self

untitle

.object_id  唯一编号

.equal?(*) 对象相等

== /eql?值相等

::  --调用常数

pack/unpack   --数组对象转换成二进制数据

指定最后一栏的字数时,可以不用指定数值,以*代替待字符串尾端的所有文字

chop 删除最后一个字符

chomp 删除行尾换行符

index/rindex --定位

include?()--包含

upcase/downcase  --大小写

swapcase --大小写转换

capticalize  --首字母大写

store

fetch  取值是不存在的话会报错 第二个参数具有优先值

each_key /each_value

reject 和 delete_if 

<< / <<-

.clear

Regexp.quote()  忽略转义字符

i 忽略大小写

s、e、u、n  指定编码方式

x 忽略空白

m 让.与换行符匹配

eof? 

lineno

getc/each_byte/ungetc

pos/seek/rewind/truncate

flush

sync

Dir.glob

mkdir/rmdir 创建和删除目录

File.basename

File.dirname

File.extname

File.split

File.join(dir,base)

File.expand_path

File.find

File.prune

tempfile.new

.close

.open

.path

FileUtils.cp

.cp_r

.cp_rf

.mv

.rm

.rm_r

.rm_rf

.compare

.install

.mkdir_p

=====================================================

.parse

.isdst 夏令时

.step(*)  步长

(0..20).step(3){|x| print x }

Arry.uniq --去除重复元素

to_set

.all?

.any?

.chunk

.even?

.count(*)

.cycle(num)

.delete(*)

File.foreach

.collect

.delete

.drop(*) 

.drop_while

each_cons(*)

.detect

.flat_map

.find

.select

.first

.grep

.group_by

.menber?()

.include?()

.minmax  

none?

parition

.regect

.take()

.entries

compact

.insert(*,*)

.assoc(*)

.at(num)

.combination(num)

.compact(*)

.concat(*)

.cycle(num)

.delete_at(num)

.fetch(num)

.fill(*)

.index(*)

.flatten(num)

.forzen?

.replace(*)

.inspect

.join

.keep_if

.permutation(num)

.pop(num)

.product(*)

.push(*)

.rassoc(*)

.repeated_combination(num)

.repeated_permutation(num)

.reverse_each

.rindex(*)

.rotate(num)

.sample(num)

.shift(*)

.shuffle(num)

.transpose

.uniq

.values_at

======================================================================

irb(main):004:0> 3 + 4 => 7 irb(main):005:0> 3 * 4 => 12 irb(main):006:0> 3 - 4 => -1 irb(main):007:0> 3 / 4 => 0 irb(main):008:0> 3.0 / 4.0 => 0.75 irb(main):009:0> 0xF => 15 irb(main):010:0> 0x3 * 0xA => 30

irb(main):011:0> 14.to_s => "14"

irb(main):012:0> "hello" + "there" => "hellothere" irb(main):013:0> "Reader".length => 6 irb(main):014:0> "Reader".reverse => "redaeR" irb(main):015:0> "reader".capitalize => "Reader" irb(main):016:0> "Reader".include?("foo") => false irb(main):017:0> "Reader".include?("ade") => true irb(main):018:0> " Reader ".strip => "Reader" irb(main):019:0> "Reader".gsub("e", "f") => "Rfadfr" irb(main):020:0> "Reader".delete("ea") => "Rdr" irb(main):021:0> "a" < "b" => true

irb(main):022:0> "Bob".between? "Adam", "Chris" => true

irb(main):023:0> "hi" * 5 => "hihihihihi"

irb(main):024:0> "Reader".crypt("ab") => "abofgDjq6JNJo"

irb(main):025:0> "Reader"[2] => 97 irb(main):026:0> ?a => 97 irb(main):027:0> 97.chr => "a"

irb(main):028:0>x = 42 =>42

irb(main):029:0> "The answer is #{x}!" => "The answer is 42!" irb(main):030:0> "The answer is #{6 * 7}!" => "The answer is 42!"

irb(main):031:0> 'The answer is #{x}!' => "The answer is \#{x}!"

irb(main):032:0> a = ["hello", 42, "world"] => ["hello", 42, "world"] irb(main):033:0> a << 5.0 * 7.5 => ["hello", 42, "world", 37.5] irb(main):034:0> a[0] => "hello" irb(main):035:0> a[6] = 'hi' * 2 => "hihi" irb(main):036:0> a => ["hello", 42, "world", 37.5, nil, nil, "hihi"] irb(main):037:0> a[99] => nil

irb(main):044:0> a => ["hello", 42, "world", 37.5, nil, nil, "hihi"] irb(main):045:0> a.compact => ["hello", 42, "world", 37.5, "hihi"] irb(main):046:0> a.join => "hello42world37.5hihi" irb(main):047:0> [10, 75, 6, 29].sort => [6, 10, 29, 75] irb(main):048:0> [[1, 2, 3], [4, 5, 6]] => [[1, 2, 3], [4, 5, 6]] irb(main):049:0> [[1, 2, 3], [4, 5, 6]].flatten => [1, 2, 3, 4, 5, 6]

irb(main):050:0> h = {:foo=>'bar', :baz=>'biff'} => {:foo=>"bar", :baz=>"biff"} irb(main):051:0> h[:foo] => "bar" irb(main):052:0> h[:unknown] => nil irb(main):053:0> h[:baz] = "new" => "new" => {:foo=>"bar", :baz=>"new"} irb(main):054:0> h.entries => [[:foo, "bar"], [:baz, "new"]]

5.class => Fixnum (2 ** 96).class => Bignum 7.5.class => Float (1..10).class => Range "foo".class => String /^foo[a-e]$/.class => Regexp :foo.class => Symbol [].class => Array {}.class => Hash

irb(main):001:0> h = {:foo=>'bar', :hi=>'there'} => {:foo=>"bar", :hi=>"there"} irb(main):002:0> h.each_key {|k| puts k} foo hi => {:foo=>"bar", :hi=>"there"} irb(main):003:0> h.each {|k,v| puts "#{k}: #{v}"} foo: bar hi: there => {:foo=>"bar", :hi=>"there"}

irb(main):004:0> n = [5, 6, 10] => [5, 6, 10] irb(main):005:0> t = 1 => 1 irb(main):006:0> n.each { |i| t *= i } => [5, 6, 10] irb(main):007:0> t => 300

irb(main):008:0> t = 1 => 1 irb(main):009:0> f = lambda { |i| t *= i } => #

irb(main):001:0> def greet(name) irb(main):002:1> puts "Hello, #{name}!" irb(main):003:1> end => nil irb(main):004:0> greet "Reader" Hello, Reader! => nil irb(main):005:0> greet 42 Hello, 42! => nil

irb(main):006:0> def print_len(item)

irb(main):007:1> puts "Len = #{item.length}"

irb(main):008:1> end

=> nil

irb(main):009:0> print_len "Reader"

Len = 6

=> nil

irb(main):010:0> print_len [1, 4, 9]

Len = 3

=> nil

irb(main):011:0> print_len 42

NoMethodError: undefined method <span class="pf">'

</span>length' for

42:Fixnum

from (irb):7:in <span class="pf">'</span>print_len'

from (irb):11

irb(main):012:0>def repeat(val, times = 5) irb(main):013:1>val.to_s * times irb(main):014:1>end =>nil irb(main):015:0>repeat "hi" =>"hihihihihi" irb(main):016:0>repeat "hi", 3 =>"hihihi" irb(main):017:0>repeat 10, 3 =>"101010"

irb(main):018:0> def add(*values) irb(main):019:1> result = 0 irb(main):020:1> values.each {|x| result += x} irb(main):021:1> result irb(main):022:1> end => nil irb(main):023:0> add 1, 2, 3, 4, 5 => 15

irb(main):001:0> class Manners irb(main):002:1> def greet(name) irb(main):003:2> puts "Hello, #{name}!" irb(main):004:2> end irb(main):005:1> end => nil irb(main):006:0> m = Manners.new => #

irb(main):008:0> m.farewell "Reader" NoMethodError: undefined method 'farewell' for #<Manners:0x404839c> from (irb):8

irb(main):009:0>class Manners irb(main):010:1>def farewell(name) irb(main):011:2>puts "Goodbye, #{name}!" irb(main):012:2>end irb(main):013:1>end =>nil irb(main):014:0>m.farewell "Reader" Goodbye, Reader! =>nil

irb(main):001:0> class Manners irb(main):002:1> def initialize(name) irb(main):003:2> @name = name irb(main):004:2> end irb(main):005:1> def greet irb(main):006:2> puts "Hello, #{@name}!" irb(main):007:2> end irb(main):008:1> def farewell irb(main):009:2> puts "Goodbye, #{@name}!" irb(main):010:2> end irb(main):011:1> end => nil irb(main):012:0> m = Manners.new "Reader" => #

irb(main):001:0> class Array irb(main):002:1> def print_tr irb(main):003:2> puts "<tr>" irb(main):004:2> each { |item| irb(main):005:3* puts " <td>#{item}</td>" irb(main):006:3> } irb(main):007:2> puts "</tr>" irb(main):008:2> end irb(main):009:1> end => nil Irb(main):010:0> ["hello","world!"].print_tr <tr> <td>hello</td> <td>world!</td> </tr> => nil

irb(main):001:0> def String.concat(s1, s2) irb(main):002:1> s1 + ' ' + s2 irb(main):003:1> end => nil irb(main):004:0> String.concat 'hi', 'bye' => "hi bye"

irb(main):001:0> class String irb(main):002:1> def self.concat(s1, s2) irb(main):003:2> s1 + ' ' + s2 irb(main):004:2> end irb(main):005:1> end => nil irb(main):006:0> String.concat 'hi', 'bye' => "hi bye"

irb(main):001:0> o = Object.new => #<Object:0x3f8feb4> irb(main):002:0> o.methods => ["inspect", "taguri", "clone", "public_methods" , "taguri=", "display", "instance_variable_defined ?", "equal?", "freeze", "methods", "respond_to?", ...many more methods listed...

irb(main):003:0> o.inspect => "#<Object:0x3f8feb4>" irb(main):004:0> o.send "inspect" => "#<Object:0x3f8feb4>"

irb(main):139:0> class Object irb(main):140:1> def method_missing(*args) irb(main):142:2> puts args irb(main):143:2> end irb(main):144:1> end => nil irb(main):145:0> o.foobar 1, 2, 3 foobar 1 2 3 => nil

def method_missing(method, *args)

irb(main):001:0> class Person irb(main):002:1> def age irb(main):003:2> @age irb(main):004:2> end irb(main):005:1> def age=(value) irb(main):006:2> @age = value irb(main):007:2> end irb(main):008:1> end => nil

irb(main):009:0>p = Person.new =>#

class Person prop :age end

irb(main):001:0> class Object irb(main):002:1> def self.prop *names irb(main):003:2> names.each { |name| irb(main):004:3* self.class_eval " irb(main):005:3" def #{name} irb(main):006:3" @#{name} irb(main):007:3" end" irb(main):008:3> self.class_eval " irb(main):009:3" def #{name}=(value) irb(main):010:3" @#{name} = value irb(main):011:3" end" irb(main):012:3> } irb(main):013:2> nil irb(main):014:2> end irb(main):015:1> end => nil

irb(main):016:0> class Person irb(main):017:1> prop :age, :name irb(main):018:1> irb(main):019:1* def initialize(age, name) irb(main):020:2> @age = age irb(main):021:2> @name = name irb(main):022:2> end irb(main):023:1> end => nil irb(main):024:0> p = Person.new(36, "Brad") => #

1)Ruby区分大小写

2)# 后跟单行注释

3)=begin 和 =end 之前的是多行注释:

=begin   

  这之间是多行注释

  也是Ruby的内嵌文档(Rdoc)注释,

  类似javadoc,可以用命令ri从源文件生产文档。   

=end  

4)分隔符

; - 分号用来分隔一行中的多个语句

() - 圆括号提高优先级,定义方法时容纳参数列表

空格 - 分隔字符,在可省略()的地方代替()

, - 逗号隔开多个参数

.  - 点将对象与它的方法隔开

:: - 双冒号域作用符,将模块(类)与它的常量隔开

5)关键字

模块定义:module

类定义: class

方法定义:def,undef

检查类型:defined?

条件语句:if,then,else,elsif,case,when,unless

循环语句:for,in,while,until,next,break,do,redo,retry,yield

逻辑判断:not,and,or

逻辑值: true,false

空值:  nil  

异常处理:rescue,ensure  

对象引用:super,self  

块的起始:begin/end

嵌入模块:BEGIN,END  

文件相关:FILE,LINE

方法返回:return

别名:  alias

6)运算符(优先级由高到低)

[]、[]=

数组下标、给数组元素赋值

**

乘冥

!、~、+、-

非、位非、一元加(正号)、负号

*、/、%

乘、除、模

+、-

加、减

>>、<<

移位:右移、左移

&

位与

^、|

位异或、位或

<=、<、>、>=

小于等于、小于、大于、大于等于

<=>、==、===、=~、!=、!~

各种相等判断(不能重写=~、!=、!~)

&&

短路与

||

短路或

..、...

区间的开始点到结束点

? :

三元条件运算符

=、%=、~=、/=、-=、+=、|=、&=、>>=、<<=、*=、&&=、||=、**=

各种赋值

defined?

检查类型

not

逻辑非

or、and

逻辑或、逻辑与

if、unless、while、until

判断与循环

begin、end

定义方法,类,模块的范围

ruby中没有"++"、"--"一类的运算符,但可以通过"+=1"、"-=1"实现

7)命名规则

Ruby 的标识符用来指向常量,变量,方法,类和模块。

Ruby的标识符区分大小写。

关键字不能用来当作常量,变量,方法,类或模块的名字。

标识符的首字符用来帮助我们确定标识所指向内容的作用域。

Ruby 使用一个约定来帮助它区别一个名字的用法:名字前面的第一个字符表明这个名字的用法:

  局部变量、方法参数和方法名称应该用一个小写字母开头或者用一个下划线开头;

  全局变量用美元符作为前缀“$”;

  而实例变量用“@”开头;

  类变量用“@@” 开头;

  类名、模块名和常量应该用大写字母开头。

词首字母后面可以是字母、数字和下划线的任意组合;“@”后面不可以直接跟数字。

Ruby  程序代码现在是用7位ACSII码来表示,通过语言扩展来支持UTF8等8位编码系统。

Ruby 2.0  版本将使用 16位的 Unicode  编码。

转载于:https://www.cnblogs.com/kinglongdai/p/8258934.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值