字符串括号/赋值和shell命令

时间:2013-01-30 18:54:01

标签: ruby

我正在使用厨师。为什么这不起作用?

someString[aSearchString]= `pwd`

对我来说,aSearchString最终不会被取代。我必须在一个单独的行上执行pwd变量,然后使用它来进行替换。

1 个答案:

答案 0 :(得分:2)

试试这个:

some_string.gsub('search_string', `pwd`)

>> s="./asd"   #=> "./asd"
>> s.gsub('.', `pwd`) #=> "/home/rahul\n/asd"
>> s.gsub('.', `pwd`.chop) #=> "/home/rahul/asd"   #chop because 'pwd` adds \n at end
>> s.gsub!('.', `pwd`.chop)  #=> "/home/rahul/asd" #inplace

基准:

ree-1.8.7-2011.12 :005 > my_bm(1000){"/./././.".gsub(".", `pwd`)}
   user     system      total        real
0.040000   0.760000   0.800000 (  2.690505)
=> nil 
ree-1.8.7-2011.12 :006 > my_bm(1000){c=`pwd`;"/./././.".gsub(".", c)}
   user     system      total        real
0.140000   0.660000   0.800000 (  2.692811)
=> nil 
ree-1.8.7-2011.12 :007 > my_bm(1000){"/./././.".gsub(".", `pwd`)}
   user     system      total        real
0.090000   0.720000   0.810000 (  2.705673)
=> nil 
ree-1.8.7-2011.12 :008 > my_bm(1000){c=`pwd`;"/./././.".gsub(".", c)}
   user     system      total        real
0.090000   0.720000   0.810000 (  2.688737)
=> nil