如何在插入数组时转义逗号

时间:2017-03-08 21:28:41

标签: arrays ruby

我有一个带逗号的变量,我想在分割数组时能够包含该逗号。

$ uname -a
Linux a 4.4.0-65-generic #86-Ubuntu SMP Thu Feb 23 17:49:58 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux

$ docker --version
Docker version 17.03.0-ce, build 3a232c8

$ docker info
Containers: 39
 Running: 1
 Paused: 0
 Stopped: 38
Images: 269
Server Version: 17.03.0-ce
Storage Driver: aufs
 Root Dir: /var/lib/docker/296608.296608/aufs
 Backing Filesystem: extfs
 Dirs: 395
 Dirperm1 Supported: true
Logging Driver: json-file
Cgroup Driver: cgroupfs
Plugins: 
 Volume: local
 Network: bridge host macvlan null overlay
Swarm: inactive
Runtimes: runc
Default Runtime: runc
Init Binary: docker-init
containerd version: 977c511eda0925a723debdc94d09459af49d082a
runc version: a01dafd48bc1c7cc12bdb01206f9fea7dd6feb70
init version: 949e6fa
Security Options:
 apparmor
 seccomp
  Profile: default
 userns
Kernel Version: 4.4.0-65-generic
Operating System: Linux Mint 18.1
OSType: linux
Architecture: x86_64
CPUs: 8
Total Memory: 15.55 GiB
Name: a-dell
ID: IEJP:6N34:GFBS:VIOM:HDBW:NVOF:BH3E:HZFO:3SOE:AACN:VZCV:FSWZ
Docker Root Dir: /var/lib/docker/296608.296608
Debug Mode (client): false
Debug Mode (server): false
Registry: https://index.docker.io/v1/
WARNING: No swap limit support
Experimental: false
Insecure Registries:
 127.0.0.0/8
Live Restore Enabled: false

最后一行将产生

myarray = ["hello", "apple"]
data = "Bahamas, The"
myarray << data
myarray.join(", ").split(",")

但我想要

["hello", " apple", " Bahamas", " The"] 

1 个答案:

答案 0 :(得分:1)

它没有多大意义,但似乎能提供你想要的东西:

myarray = %w(hello apple)
data = 'Bahamas, The'
myarray << data
placeholder = '##<<$$COMMA$$>>##'
p myarray.map { |s| s.gsub(',', placeholder) }
         .join(', ')
         .split(',')
         .map { |s| s.gsub(placeholder, ',') }

#=> ["hello", " apple", " Bahamas, The"]

实际上,这个连接/拆分只是为除第一个元素之外的所有元素添加了一个空格。所以你可以写:

myarray = %w(hello apple)
data = 'Bahamas, The'
myarray << data

p myarray.map.with_index { |s, i| i == 0 ? s : ' ' + s }
#=> ["hello", " apple", " Bahamas, The"]