ruby中星號(*)的功用

ruby中星號(*)的作用

有正常的乘法功能

  3 * 4 == 12 # => true

數組*integer

 [1,2,3] * 2 =  [1, 2, 3, 1, 2, 3] ;


 [1,2 ,[3 , [4 ,5]]] *2 = [1,2 ,[3 , [4 ,5]] , 1,2 ,[3 , [4 ,5]]]

  
3. 字符串*integer

"hello"*2 = "hellohello"

4.創建數組

*a = 1,3,"as" # => 相當於 a = [1,3, "as"]

  
5. 數組參數傳入時的前綴eg:

  a= [1 , 2] 
 demoFun(*a) == demoFun(1 , 2) #正確
 demoFun(*a)== demoFun([1,2])#錯誤
 
 demoFun(*a) 等同於 demoFun(1,2)

6.查詢sql:

sql:
values = ['小明',15]
User.where('name=? and age = ?', *values) #=> 等同於 User.where('name=? and age = ?', "小明",'15')

7.hash中的含義

Hash[:a, 1, :b, 2] # => {:a => 1, :b => 2}
array = [:a, 1, :b, 2] 
Hash[array] # => {} 
Hash[*array]#=> 相當於 Hash[:a, 1, :b, 2] #=> {:a => 1, :b => 2}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章