常用小技巧

1 ruby  hash to array
  {a: 1, b: '2'}.map{|k,v| "#{k} = #{v}"}

  # => ['a=1','b=2']

  arr = [["a", "1"], ["b", "2"], ["c", "3"], ["d", "4"]]

  Hash[arr]

  # =>  {"a"=>"1", "b"=>"2", "c"=>"3", "d"=>"4"}


2 ruby get array element
  arr = ["item 1", "item 2", "item 3", "item 4"]
  a,b,c d = *arr

  a # => item 1
  b # => item 2
  c # => item 3
  d # => item 4


3 ruby array to  hash
  a = ["item 1", "item 2", "item 3", "item 4"]
  h = Hash[*a]

  # => {"item 1"=>"item 2", "item 3"=>"item 4"}



4 ruby two array element  adding 

  a = [1,2,3,4]

  b = [5,6,7,8]

  a.zip(b)

  # = > [[1,5],[2,6],[3,7],[4,8]]

  a.zip(b).map{|x,y| x + y}

  # => [6,8,10,12]


5 ruby Regexp  return true or false

/^\(\d{3}\)\s{1}\d{3}-\d{4}$/ === "(123) 456-7890"

# => true


6 ruby string format

  '(%d%d%d) %d%d%d-%d%d%d%d' % [1,2,3,4,5,6,7,8,9,0]

  # => (123) 456-7890


7 ruby string to array

   str = "a=1, b=2, c=3, d=4, dddd"

   arr1 = str.split(', ')

   # => ["a=1","b=2","c=3","d=4","dddd"]


   arr2 = str.scan(/\w=\d/)

   # => ["a=1", "b=2", "c=3", "d=4"]

  
8 ruby string append

  str = ''

  str << 'a'  # => 'a'

  str << 'b'  # => 'ab'

  str << 'c'  # => 'c'

9 ruby string insert

  str = 'world'

  str.insert(0,'hello')

  # => 'hello world'

你可能感兴趣的:(小技巧)