显示标签为“Ruby Cookbook”的博文。显示所有博文
显示标签为“Ruby Cookbook”的博文。显示所有博文

2007年1月19日星期五

Regular Expression In Ruby Language

Four ways of writing regular expression in ruby:
  1. /something/
  2. Regexp.new("something")
  3. Regexp.compile("something")
  4. %r{something}

Regexp::MULTILINE m
Normally, a regexp matches against a single line of a string. This will cause a regexp to treat line breaks like any other character.

Regexp::IGNORECASE i
Makes matches case-insensitive


Regexp::EXTENDED x
This modifier lets you space out your regular expressions with whitespace and comments, making them more legible.

一篇关于ruby中正则表达式的文章翻译
原文出处: http://www.regular-expressions.info/ruby.html

Ruby中正则表达式的修饰符(译)

在Ruby中使用正则表达式 Ruby支持正则表达式作为其一项语言特性。在Ruby中,正则表达式被写作 /模版/修饰符 的形式,这里的"模版"就是正则表达式本身,而"修饰符"则是一系列不同选项字符的标识,另外,"修饰符"部分是可选的。这个语法特点从Perl借鉴而来。 Ruby支持如下的修饰符: /i 使正则表达式大小写不敏感(正则表达式本身是大小写敏感的) /m 使"."匹配新行。Ruby使用/m,然而Perl和其他很多编程语言使用/s来实现"点(.)匹配新行"。 /o 它将致使任何的 #{...}替换符在一个特殊的正则表达式中仅仅被执行一次,它在第一次会被求值。然而,如果没有用/o,替换符将会每次都执行,并且产生一个Regexp对象。
你能同时使用如上的修饰符象这样: /rgex/is
在Ruby中,^字符号和$符号总是匹配新行的前后。Ruby没有修饰符能够改变这个特点。使用\A 和 \Z 可以匹配在字符串的始端或者末端。 因为正斜杆界定了正则表达式的长度,所以任何出现在正则表达式中的正斜杆都将被除去。例如,在ruby中,正则表达式 1/2 被写做 /1\/2/ (这里隐藏了含义,即反斜杆\,通常被我们成为转义符)

2007年1月13日星期六

Case of String


Here,there are methods about case of string in Ruby language.
1.String#upcase
2.String#upcasedowncase
3.String#swapcase
4.String#capitalize
5.String#capitalize_first_letter

All four methods have corresponding methods that modify a string in place rather than creating a new one: upcase!, downcase!, swapcase!, and capitalize!. Assuming you don't need the original string, these methods will save memory, especially if the string is large.



To change the case of specific letters while leaving the rest alone, you can use the TR or TR! methods, which translate one character into another:

'LOWERCASE ALL VOWELS'.tr('AEIOU', 'aeiou')
# => "LoWeRCaSe aLL VoWeLS"


2007年1月10日星期三

Ruby Continue~~


In recipe 1.4, there is a example:
"Three little words".split(/\s+/)
#=>["Three","little","words"]
"Three little words".split(/(\s+)/)
#=>["Three"," ","little"," ","words"]

Here,when I firstly looked at,I confused. But then I think about it carefully,I got way~! In regular expression /(\s+)/, parentheses make spaces stored. Because parentheses in regular expressions, it make the characters of including by parentheses stored in memory,then u can use \1 to reference it after parentheses.



A important tip in recipe 1.5. Special characters are only interpreted in strings delimited by double quotes, or strings created with %{} or %Q{}, but single quotes and %q{} are not.

puts "foo\tbar"
#=>"foo bar"
puts %{foo\tbar}
#=>"foo bar"
puts %Q{foo\tbar}
#=>"foo bar"

puts 'foo\tbar'
#=>"foo\tbar"
puts %q{foo\tbar}
#=>"foo\tbar"




In Recipe 1.6, I got three ways to convert between charactors and values.
1.use ? charactor
?a
#=>97
2.use to access a element of array
'a'.[0]
#=>97
3.from ascii to char,use #chr method
97.chr
#=>"a"

2007年1月9日星期二

Symbol and String


A Symbol is about the most basic Ruby object you can create. It's just a name and an internal ID. Symbols are useful becase a given symbol name refers to the same object throughout a Ruby program.In Rails,we usually use this point,such as ":action=>welcome" and so on. If you wanna get the corresponding symbol of a given string,String.intern will be.

name ="allen"

puts :allen
#=>"allen"
puts name
#=>"allen"

puts :allen.object_id
#=>190498
puts name.intern.object_id
#=>190498
puts name.object_id
#=>21723660




In Rails, we can see the symbol around web application code.Let's think about it!
Hem.......because symbol don't allocate another memory,it doesn't like string.

puts "allen".object_id
#=>21723550
puts "allen".object_id
#=>21723490
puts :allen.object_id
#=>190498
puts :allen.object_id
#=>190498

Substituting variables into an Existing String

From last recipe,we know a way of substituting variables into string. Here, there are some ways again.



1. Printf-style string format
var = 'My name is %s.'
var % 'Allen'
#=> "My name is Allen."
'To 2 decimal places: %.2f' % Math:PI
#=> "To 2 decimal places: 3.14"
'Zero-padded: %.5d' % Math:PI
#=> "Zero-padded: 00003"




2.Use ERB
require 'erb'

template = ERB.new %q{It is <%= var%>!}
var = "here"
# When var is binded to template,just like following
puts template.result(binding)
#=> print "It is here"

2007年1月7日星期日

About Substituting Variables


Usually,we use such as #{var} for substituting variables into string.
eg.
  var="Allen"
  puts "My name is #{var} ."
  #=>"My name is Allen ."



And if you wanna use string interpolation more complex, you can do just like this:
  %{Here is #{class InstantClass
   def bar
    "some text"
   end
  end
  InstantClass.new.bar
  }.}
  # => "Here is some text."



Here, a way to avoid triggering string interpolation
1.Escape the hash characters
"\#{var}"    # => "\#{var}"
2.Put the string in single quotes
'#{var}'    # => "\#{var}"




Ways of multiline for string
1.Use %{}
2.Use =<< END .. END,here, 'END' is a tag of starting and ending for multiline string.

Ruby Cookbook

终于狠了心买了《Ruby Cookbook》,电子版本看着太费眼神,纸质的感觉始终留着书香:)决定好好看看Ruby,因为写RoR的时候,感觉Ruby基础太弱,以致于很多概念,包括Plugin的使用都不是很顺手,以后每天都抽出时间看几个Recipe,嘿嘿,Ok,let's
look at it.


Recipse 1.1 Building a String from Parts


hash = {'key1'=>'val1','key2'=>'val2'}
string = ""



# don't code like following,
# because it makes new String object,wastes time and memory
hash.each {|k,v| string << "#{k} is #{v}\n"}



# more efficient way like this:
hash.each {|k,v| string << k << " is " << v << "\n" }



data = ['1','2','3']
data.join('|')
# => 123
# another way to simulate the behavio of Array#join across an iteration
s=""
data.each_with_index {|x,i| s << x; s << "|" if i < data.length-1 }
puts s
# => 123