`

Ruby on Rails字符串处理(1)

阅读更多

创建字符串

Ruby中创建一个字符串有多种方式。可以有两种方式表示一个字符串:用一对单引号包围字符('str')或用一对双引号包围字符("str") 这两种形式的区别在于对于包围的字符串的处理,用双引号构造的字符串能处理更多的转移字符。 

除了这两种方式,ruby还支持3种方式去构建字符串:%q%Qhere documents。 

%q后面用一对分界符包围的字符可以构造单引号字符串。 

%Q后面用一对分界符包围的字符可以构造双引号字符串。 

PS:分界符可以是任何一个非字母数字的单字节字符,如() [] {} <> //

here documents 

str=<<END_OF_STRING

  a string

END_OF_STRING

ruby中并不会去掉字符串开头的空格。 

 

#5种构建字符串hello world的方法对比

'hello world'

"hello world"

%q/hello world/

%Q{hello world}

str=<<EOS

  hello world

EOS

单引号和双引号在某些情况下有不同的作用.一个由双引号括起来的字符串允许字符由一个前置的斜杠引出,而且可以用#{}内嵌表达式.而 单引号括起来的字符串并不会对字符串作任何解释

 

Ruby的字符串操作比C更灵巧,更直观.比如说,你可以用+把几个串连起来,*把一个串重复好几遍

"foo" + "bar"   #"foobar" 

"foo" * 2      # #"foofoo"

抽取字符(注意:Ruby,字符被视为整数):

负的索引指从字符串尾算起的偏移量,

word[0]

word[-1]

herb[0,1] 

herb[-2,2] 

herb[0..3] 

herb[-5..-2] 

检查相等

"foo" == "foo" 

 

字符串基本操作

ruby中常用的简单字符串处理函数

split()

trim()

indexOf()

replaceAll()

String.split

"hello world".split( " ")

returns [ "hello", "world" ].

String.strip

" hello world ".strip

returns "hello world".

String.index

"hello world".index( "w")

returns 6.

String.gsub(/\s/, ',')

"hello word".gsub(\/s\, ',')

returns "hello,word"

p.s.

sub() replace first

gsub() replace all

 

1、字符串定义与产生

str1 = 'Hello world'

str2 = "Hello world"   #双引号比单引号定义的字符串更加强大,如可提供转移字符等

str3 = %q/Hello world/ # %q将后面的字符串转换成单引号字符串,后面的/为自定义的特殊符号,在字符串结尾处也需有该特殊符号

str4 = %Q/Hello world/ # %Q将定义双引号字符串

str = <<The_Text Hello World! Hello Ruby. The_Text

puts str        #这种方式比较有意思,str的内容为<<The_Text到下个The_Text之间的内容,The_Text为自定义的文本

arr = [1,1,1,2,2]

puts arr.join(",")    #数组用join转换成字符串

2、字符串操作

str = 'this' + " is"

str += ' you'

str <<" string"<<"."

puts str * 2 #this is you string.this is you string.

puts str[-12,12] # you string. 意味从后截取多少个字符

3、转义字符串

\n   \t  \'

字符串转移只对双引号字符串生效,例外为单引号,如:

str = 'this\'s you string.'

 

字符串内嵌入表达式用  #{ }

def Hello(name)

  "Hello #{neme}!"

end

 

4、删除

str.delete(str1,str2,...) 

#删除参数交集出现的所有字符,返回一个新字符串,如:

"hello world".delete("l") #返回"heo word"

"hello world".delete("lo","o") #返回"hell wrld"str.delete!(str1,str2,...) 

#直接对str进行删除操作,同时返回str如:

str="hello world"

str2=str.delete("l")  #str"hello world",str2"heo word"

str.delete!("l") #str"heo word"

5.字符串替换

str.gsub(pattern, replacement)  => new_str  

str.gsub(pattern) {|match| block }  => new_str  

"hello".gsub(/[aeiou]/, '*')  #=> "h*ll*" #将元音替换成*号  

"hello".gsub(/([aeiou])/, '<\1>')  #=> "h<e>ll<o>" #将元音加上尖括号,\1表示保留原有字符???  

"hello".gsub(/./) {|s| s[0].to_s + ' '} #=> "104 101 108 108 111 "  

字符串替换二:

str.replace(other_str) => str  

s = "hello" #=> "hello"  

s.replace "world" #=> "world" 

6.字符串删除:

str.delete([other_str]+)  => new_str  

"hello".delete "l","lo"  #=> "heo"  

"hello".delete "lo"  #=> "he"  

"hello".delete "aeiou", "^e"  #=> "hell"  

"hello".delete "ej-m"  #=> "ho" 

7.去掉前和后的空格

str.lstrip => new_str  

" hello ".lstrip #=> "hello "  

"hello".lstrip #=> "hello" 

8.字符串匹配

str.match(pattern) => matchdata or nil 

9.字符串反转

str.reverse => new_str  

"stressed".reverse #=> "desserts" 

10.去掉重复的字符

str.squeeze([other_str]*) => new_str  

"yellow moon".squeeze #=> "yelow mon" #默认去掉串中所有重复的字符  

" now is the".squeeze(" ") #=> " now is the" #去掉串中重复的空格  

"putters shoot balls".squeeze("m-z") #=> "puters shot balls" #去掉指定范围内的重复字符 

11.转化成数字

str.to_i=> str  

"12345".to_i #=> 12345 

 

12、chomp和chop的区别:
chomp:去掉字符串末尾的\n或\r
chop:去掉字符串末尾的最后一个字符,不管是\n\r还是普通字符

"hello".chomp  #=> "hello"  

"hello\n".chomp  #=> "hello"  

"hello\r\n".chomp  #=> "hello"  

"hello\n\r".chomp  #=> "hello\n"  

"hello\r".chomp  #=> "hello"  

"hello".chomp("llo")  #=> "he"  

"string\r\n".chop  #=> "string"  

"string\n\r".chop  #=> "string\n"  

"string\n".chop  #=> "string"  

"string".chop  #=> "strin" 

13、长度

#求字符串长度,返回int

str.size

str.length

 

14、特殊字符处理

str.chop 

#删除字符串str的最后一个字符,并返回新字符串

#若字符串以\r\n结尾,则两个字符都删去

#若字符串为空串,则返回空串

"string\r\n".chop  #返回"string"

"string\n\r".chop  #返回"string\n"

"string".chop      #返回"strin"

"s".chop.chop      #返回""str.chop! 

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

str.chompendstr) 

#删除str的后缀endstr

#如果未指定endstr,则删除回车换行符(\r\n\r\n)

"hello\r\n".chomp  #返回"hello"

"hello".chomp("lo")#返回"hel"

"hello".chomp("l") #返回"hello"str.chomp! 

 

15、Ruby字符串处理函数包括返回字符串长度函数;

"hello".include? "lo"

 

16、Ruby生成随机数和随机字符串

rand(100000)

def newpass( len )

      chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a

       newpass = ""

       1.upto(len) { |i| newpass << chars[rand(chars.size-1)] }

       return newpass

end

puts   newpass(15)

1
1
分享到:
评论

相关推荐

    Ruby On Rails中文教材(PDF)

    Ruby on Rails,简称Rails,是一款基于Ruby语言的开源Web应用框架,它遵循MVC(Model-View-Controller)架构模式,旨在简化Web应用程序的开发。Rails由David Heinemeier Hansson于2004年创建,它提倡“约定优于配置...

    Ruby on Rails安装包全集(Linux)

    Ruby在处理字符串和正则表达式时会用到这个库。 3. **lighttpd-1.4.11.tar.gz**: Lighttpd是一个轻量级的Web服务器,适合用于资源有限的环境,如嵌入式设备或个人服务器。在Ruby on Rails开发中,它可以作为应用的...

    ruby on rails api

    5. **ActiveSupport**:提供了一系列有用的工具和库,如时间助手、字符串操作、哈希扩展等,增强了Ruby的基础功能。 6. **Routes**:Rails的路由系统将URL映射到控制器的行动上,定义了应用的导航结构。 7. **...

    Ruby on Rails入门经典

    1. **Ruby语言基础**:首先,你需要了解Ruby的基础语法,包括变量、数据类型(如字符串、整数、浮点数、数组、哈希)、控制结构(如条件语句if/else,循环for、while、each)、函数定义与调用、类和对象等概念。...

    ruby on rails 2.2.2 参考手册

    7. **ActiveSupport**:这个库包含了各种实用工具和扩展,如时间辅助方法、字符串操作等,广泛应用于Rails项目。 8. **测试**:Rails内置了测试框架,包括Unit Test、Functional Test和Integration Test,通过`test...

    Ruby on Rails Bible.pdf

    根据提供的文件信息,“Ruby on Rails Bible.pdf”这本书涵盖了Ruby on Rails框架的基础知识、核心概念以及高级功能等内容。接下来,我们将从书中的章节标题入手,详细阐述各章节所涉及的重要知识点。 ### 引言 ...

    Ruby on rails开发从头来

    在Ruby中,一切都是对象,包括基本数据类型如整数、字符串和布尔值。Ruby强调代码的可读性和简洁性,这使得它成为快速开发的理想选择。 Ruby on Rails的核心理念是DRY(Don't Repeat Yourself)和Convention Over ...

    基于Ruby语言的Ruby on Rails项目及其代码方案

    - **说明**:此命令用于创建一个名为User的模型,并包含两个字段:name(字符串类型)和email(字符串类型)。 - **执行结果**:会生成对应的模型文件以及数据库迁移文件。 3. **更新数据库** - **命令**: ```...

    Ruby On rails依赖的目录树

    3. **activesupport (3.2.3)**:Active Support是Rails的核心工具箱之一,提供了一系列辅助类和模块,用于字符串操作、缓存机制、时间处理等。 4. **builder (3.0.0)**:提供了生成XML文档的能力,这对于构建动态...

    ruby on rails资料

    学习Ruby时,需要掌握关键字、符号、字符串、数组、哈希等数据类型,以及如何进行异常处理和文件操作。 接着是“ruby中文文档”,这通常包括官方文档的中文版,涵盖了Ruby的各个方面,如标准库、API、语言规范等。...

    Ruby on Rails开发指南

    理解Ruby的基本数据类型(如字符串、整数、数组、哈希)、控制结构(如if语句、case语句、循环)以及面向对象特性(类、继承、模块)是学习Rails的前提。 2. **Rails框架结构**:Rails采用MVC架构,其中Model负责...

    征服 Ruby On Rails(源代码光盘)

    在Ruby中,一切皆为对象,包括基本类型如数字、字符串和布尔值。Ruby支持元编程,允许在运行时修改或创建类和方法,这使得代码更加灵活。 二、Rails框架介绍 Rails是由David Heinemeier Hansson开发的,其设计哲学...

    ruby on rails API

    Ruby on Rails(简称Rails)是一个基于Ruby语言的开源Web应用程序框架,它遵循MVC(Model-View-Controller)架构模式,极大地简化了Web应用开发。API(Application Programming Interface)是Rails提供的一种允许...

    ruby on rails 2.1新特性介绍

    - **Ruby 1.9兼容性**:随着Ruby语言的不断进步,Rails 2.1全面支持Ruby 1.9,充分利用了新版本语言的性能提升和新特性,如Fibers和新的字符串处理功能。 #### 调试和Bug修复 - **调试工具的增强**:Rails 2.1加强...

    Ruby on Rails Web开发之旅.pdf【第二部分】

    第1章 Ruby on Rails简介 1.1 历史 1.2 开发原则 1.2.1 惯例优先 1.2.2 不重复自我 1.2.3 灵活的开发 1.3 构建wleb应用程序示例 1.3.1 digg简介 1.3.2 应用程序示例的特性 1.4 小结 第2章 技术准备  2.1 所需软件...

    Ruby on Rails Web开发之旅.pdf【第一部分】

    第1章 Ruby on Rails简介 1.1 历史 1.2 开发原则 1.2.1 惯例优先 1.2.2 不重复自我 1.2.3 灵活的开发 1.3 构建wleb应用程序示例 1.3.1 digg简介 1.3.2 应用程序示例的特性 1.4 小结 第2章 技术准备  2.1 所需软件...

    Ruby on Rails Web开发之旅.pdf【第三部分】

    第1章 Ruby on Rails简介 1.1 历史 1.2 开发原则 1.2.1 惯例优先 1.2.2 不重复自我 1.2.3 灵活的开发 1.3 构建wleb应用程序示例 1.3.1 digg简介 1.3.2 应用程序示例的特性 1.4 小结 第2章 技术准备  2.1 所需软件...

    ruby和rails简介

    3. **面向对象**:一切在Ruby中都是对象,包括基本的数据类型如整数和字符串。 4. **元编程能力**:Ruby支持高级的元编程技术,允许开发者在运行时修改或扩展语言本身。 #### Rails框架介绍 Ruby on Rails(简称...

Global site tag (gtag.js) - Google Analytics