Blog信息 |
blog名称: 日志总数:1304 评论数量:2242 留言数量:5 访问次数:7572214 建立时间:2006年5月29日 |

| |
[Ruby on Rails]〈ruby cookbook>第一章:String 软件技术
lhwork 发表于 2007/2/7 9:03:44 |
1.Building a String from Parts:
In ruby,String is mutable,you can build a String from a hash like this:
hash = { "key1" => "val1", "key2" => "val2" }string = ""hash.each { |k,v| string << "#{k} is #{v}/n" }puts string
2.Subsituting Variables into Strings:
Within the string, enclose the variable or expression in curly brackets and prefix it with a hash character. number = 5
"The number is #{number}." # => "The number is 5."
then you can see the power of this feature through next example: %{Here is #{class InstantClass def bar "some text" endendInstantClass.new.bar}.}# => "Here is some text."3.The "here document" construct,for example:<<end_of_poemThere once was a man from PeruWhose limericks stopped on line twoend_of_poem 4。Reverse a String by Words or Characters(1)by characters:s = ".sdrawkcab si gnirts sihT"s.reverse! # => "This string is backwards."(2)by words:s = "order. wrong the in are words These"s.split(/(/s+)/). reverse!.join('') # => "These words are in the wrong order."s.split(//b/).reverse!.join('') # => "These words are in the wrong. order"The String#split method takes a regular expression to use as a separator. 5.(1)character -> anscii code:?a # => 97?! # => 33(2)string -> anscii code:'a'[0] # => 97(3)number -->anscii character:97.chr # => "a"33.chr # => "!"6. Converting Between Strings and Symbols:to_s to_sym String#intern7.Processing a String One Character at a Time:String#each_byte String#scan8.Changing the Case of a String:String#swapcase String#upcase String#downcase String#capitalize9. (1)remove whitespace from the beginning and end of a string: " /tWhitespace at beginning and end. /t/n/n".stripwe also have String#lstrip and String#rstrip methods!
(2)Add whitespace to one or both ends of a string with ljust, rjust, and center: s = "Some text."
s.center(15)
s.ljust(15)
s.rjust(15)
(3)Use the gsub method with a string or regular expression to make more complex changes 10.Testing Whether an Object Is String-Like 'A string'.respond_to? :to_str # => trueException.new.respond_to? :to_str # => true4.respond_to? :to_str # => false11.Getting the Parts of a String You Want:s = 'My kingdom for a string!'s.slice(3,7) # => "kingdom"s[3,7] # => "kingdom"s[15…s.length] # => "a string!"12.Validating an email address: def probably_valid?(email)valid = '[A-Za-z/d.+-]+' #Commonly encountered email address characters(email =~ /#{valid}@#{valid}/.#{valid}/) == 0end13.Generating a Succession of Strings:'89999'.succ # => "90000"'nzzzz'.succ # => "oaaaa" |
|
|