Ruby中創(chuàng)建字符串的一些技巧小結(jié)
%{String} 用于創(chuàng)建一個使用雙引號括起來的字符串
%Q{String} 用于創(chuàng)建一個使用雙引號括起來的字符串
str=<<END_OF_STRING
a string
END_OF_STRING
%Q!Some String of “Characters”! <==> ” Some String of /”Characters/” “
%q{String} 用于創(chuàng)建一個使用單引號括起來的字符串
%q!Some String of “Characters”! <==> ‘Some String of Characters'
%r{String} 用于創(chuàng)建一個正則表達式字面值
%r{/usr/bin/} <==> ///usr//bin///
%w{String} 用于將一個字符串以空白字符切分成一個字符串數(shù)組,進行較少替換
%W{String} 用于將一個字符串以空白字符切分成一個字符串數(shù)組,進行較多替換
%W(North South East West) <==> ["North", "South", "East", "West"]
%s{String} 用于生成一個符號對象
%x{String} 用于執(zhí)行String所代表的命令
%x{ ls /usr/local } <==> `ls /usr/local`
PS:上面幾個%表示法中用{}擴住了String,其實這個{} 只是一種分割符,可以換成別的字符,比如(),那么%表示法就是%(String),當然還可以是別的字符,對于非括號類型的分割符,左右兩邊要相同, 如%!String!
下面我對這些表示法簡單舉幾個例子:
%{String}用于創(chuàng)建一個使用雙引號括起來的字符串
這個表示法與%Q{String}完全一樣,這邊直接句個例子看結(jié)果:
result = %{hello}
puts "result is: #{result}, Type is:#{result.class}"
結(jié)果: result is: hello, Type is:String
%Q{String}用于創(chuàng)建一個使用雙引號括起來的字符串
%q{String}用于創(chuàng)建一個使用單引號括起來的字符串
從說明中可以看出這兩個表示法的區(qū)別就是一個使用雙引號,一個使用單引號。使用雙引號的字符串會對字符串中的變量做較多替換,而單引號則做較少的替換,具 體看例子。先看%Q{String}:
world = "world"
result = %Q{hello #{world}}
puts "result is: #{result}, Type is:#{result.class}"
結(jié)果: result is: hello world, Type is:String
換成%q{String}:
world = "world"
result = %q{hello #{world}}
puts "result is: #{result}, Type is:#{result.class}"
結(jié)果:
result is: hello #{world}, Type is:String
從上面的結(jié)果可以看出,較少替換的情況下,#{world}被解析成了字符串,而不會去計算這個變量中的值。
%r{String}用于創(chuàng)建一個正則表達式字面值
就像使用/reg/方式一樣,看代碼:
result = %r{world}
puts result =~ "hello world"
puts "result is: #{result}, Type is:#{result.class}"
結(jié)果: 6
result is: (?-mix:world), Type is:Regexp
可以看出,world從第6個字符開始匹配
%w{String}用于將一個字符串以空白字符切分成一個字符串數(shù)組,進行較少替換
%W{String}用于將一個字符串以空白字符切分成一個字符串數(shù)組,進行較多替換
這兩個應(yīng)該是大家見過最多的,用這個方式構(gòu)造數(shù)組,可以省下一些逗號,Ruby真 是會慣壞大家,以后大家都不用標點符號了。
同樣給一個簡單的例子:
result = %w{hello world}
puts "result is: #{result}, Type is:#{result.class}, length is:#{result.length}"
結(jié)果: result is: helloworld, Type is:Array, length is:2
%s{String}用于生成一個符號對象
直接先上代碼:
result = %s{hello world}
puts "result is: #{result}, Type is:#{result.class}"
sym = :"hello world"
puts "the two symbol is the same: #{sym == result}"
結(jié)果:
result is: hello world, Type is:Symbol
the two symbol is the same: true
可以看出,這兩中方式生成的symbol對象完全一樣
%x{String}用于執(zhí)行String所代表的命令
比如:
%x{notepad.exe}可以啟動windows下的記事本,這里我就不列結(jié)果了(那是一個大家熟悉的窗口)
相關(guān)文章
ruby元編程之創(chuàng)建自己的動態(tài)方法
這篇文章主要介紹了ruby元編程之創(chuàng)建自己的動態(tài)方法,本文講解使用method_missing和respond_to?創(chuàng)建自己的動態(tài)方法,需要的朋友可以參考下2015-05-05Ruby中的方法(函數(shù))學(xué)習(xí)總結(jié)
這篇文章主要介紹了Ruby中的方法(函數(shù))學(xué)習(xí)總結(jié),本文講解了函數(shù)的命名規(guī)則、函數(shù)參數(shù)、返回值等內(nèi)容,需要的朋友可以參考下2014-11-11Ruby on Rails在Ping ++ 平臺實現(xiàn)支付
本文給大家分享的是使用Ruby on Rails在Ping ++ 平臺實現(xiàn)支付功能的代碼,非常的實用,有需要的小伙伴可以參考下。2016-02-02