设为首页 加入收藏

TOP

ruby 基础知识(一)(三)
2017-10-10 12:07:40 】 浏览:2469
Tags:ruby 基础知识
nbsp;# 9.64883412646315
 
十四 load  require
 
require,load用于包含文件;include,extend则用于包含模块。
 
require加载文件一次,load加载文件多次。
 
require加载文件时可以不加后缀名,load加载文件时必须加后缀名。
 
require一般情况下用于加载库文件,而load用于加载配置文件。
 
利用load 多次加载文件的特性,可以用来实现程序的无缝升级和系统的热部署。程序功能改变了,你只需要重新load 一次,其它代码与它再次交互的时候,这个程序实际上已经不是原来的程序了
 
十五   字符串详解
 
str1 = 'this is str1'
str2 = "this is str2"
str3 = %q/this is str3/
str4 = %Q/this is str4/
 
str5 = <<OK_str
Here is string document, str5
line one;
line two;
line three.
OK
OK_str
 
puts str3
puts str4
puts str5
运行结果:
this is str3
this is str4
 
Here is string document, str5
line one;
line two;
line three.
OK
 
1.%q 用来生成单引号字符串;%Q用来生成双引号字符串。%q或者%Q后面跟着的是分隔符,可以是配对的! !; / /; < >; ( ); [ ] ;{ };等等
 
2.str5是一个字符串文档,从 <<文档结束符的下一行开始,直到遇到一个放置在行首的文档结束符,结束整个字符串文档。
 
3.一个数组可以用join 方法转换成字符串,join( ) 内的参数也是一个字符串,用来分隔数组的每个元素,例如:arr.join(", ")
 
4.字符串操作
 
(1)
str = ' this' + " is"
str += " you"
str << " string" << " ."
 
puts str*2   # this is you string . this is you string .
 
 
str = " \tthis is you string ."
puts str  #    this is you string .
 (2) 字符串内嵌表达式
 
Ruby表达式在 #{ } 之中,这些表达式在使用这个字符串的时候被计算出值,然后放入字符串
 
def hello(name)
    " Welcome, #{name} !"
end
 
puts hello("kaichuan") # Welcome, kaichuan !
puts hello("Ben") # Welcome, Ben !
十六 正则表达式
 
1.Ruby中,可以使用构造器显式地创建一个正则表达式,也可以使用字面值形式 /正则模式/ 来创建一个正则表达式
 
str="Hello,kaichuan,Welcome!"
puts str =~ /kaichuan/ #6
puts str =~ /a/ #7
puts str =~ /ABC/ #nil
 
在字符串str中找我的名字 kaichuan。找到了,在字符串str的第6个字符处。和数组一样,字符串的起始索引位置是0。
 
2.不匹配一个正则表达式,用“!~” ,不能用“!=”。 “!~”用来断言不符合一个正则表达式,返回 true,flase
 
str="Hello,kaichuan,Welcome!"
puts str !~ /kaichuan/ # false
puts str !~ /a/ # false
puts str !~ /ABC/ # true
 
3.将文章中所有的windows2000 或者 windows98 换成 Windows XP,不论单词开头大小写,但是不带数字的windows不换;并且要把2006年12月31日改成当前时间
 
strdoc=<<DOC_EOF
This is windows2000 or windows98 system.
Windows system is BEST?
Windows2000 running in 12-31-2006,……
DOC_EOF
 
re = /[w|W]indows(?:98|2000) /
strdoc.gsub!(re, "Windows XP ")
re = /[1-9][0-9]\-[1-9][0-9]\-\d\d\d\d/
time = Time.now.strftime("%m-%d-%Y")
strdoc.gsub!(re, time)
puts strdoc
strdoc.gsub!(re, "Windows XP "),是把字符串strdoc里所有匹配正则模式re的子串替换为 "Windows XP "。 gsub!是替换所有子串
 
strdoc.gsub!(re, time),是把字符串strdoc里所有匹配正则模式re的子串替换为字符串time。
 
time = Time.now.strftime("%m-%d-%Y"),取出系统当前时间,并且格式化成( 月-日-年 )的形式,生成一个字符串time。
 
十七 迭代器、代码块、闭包
 
1. 
(1..9).each {|i| print i if i<7}
迭代器each 是数组类的一个方法;大括号{ }里的代码是代码块,简称块。你可以用大括号{ }将代码组织成块,也可以用 do…end将代码组织成块。大括号{ }的优先级高于do…end
 
2.调用一个块要用关键字yield。每一次 yield,块就被调用一次
def one_block
    yield
&nbs
首页 上一页 1 2 3 4 下一页 尾页 3/4/4
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇ruby语言是什么东西 下一篇Ruby中对象数组排序

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目