常用小技巧

本文深入探讨了Ruby编程语言中的核心概念与实用技巧,通过多个示例展示了如何使用Ruby进行数组、哈希表操作,以及正则表达式、字符串处理等常见任务。文章旨在为编程爱好者提供一个全面而具体的指南,帮助他们提升编程能力。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值