2011-11-18 63 views
1

假设我有串像下面的数组:重新组织的数组元素在我的情况

str_arr=["10$", "10$ I am a student","10$Good","10$ Nice weekend!"] 

我想重新组织的方式数组元素的值,在数组中的每个元素,如果有(有)之后10$标志白色空间(一个或多个),然后,用以下单词结合10$

正在生成类似以下的新数组:

str_arr=["10$", "10$I am a student","10$Good","10$Nice weekend!"] 

我试图做的是类似以下内容:

str_arra.map{|elem| 
    # not sure how to do here, 
    #split and check then combine again? 
     if elem.size>1 
     words=elem.split() 
     if words[0]=='10$' 
      #not sure how to do here 
     end 
     elsif elem.size==1 
     elem 
     end 


} 

但不知道如何生成新的数组...和代码上面显得冗长...

PS很可能有多的空格10$后,然后是一个字

回答

1

如果你只有这种情况下,下面应该做的伎俩:

["$ abc", "$str"].map {|v, k| v.sub(/\$ +/, '$')} 

下面是一个例子:http://codepad.org/XHeo7E8B

+0

但它也有可能是有多重$ sign之后的空白空间 – Mellon

+0

是的,这可能会导致崩溃 – apneadiving

+0

@Mellon我已修复代码以适用于多个空间 - 您应该指定具体的数据类型(您称为“空白区域”)。 – deviousdodo

1

这样做:

str_arra.map{|elem| elem.gsub(/^\$ /, "$") }