新手问题 新手关于 ruby 符号 &. 的问题,不明白是什么意思?如何定义做到可以这样使用的?

Allen_hui · September 03, 2019 · Last by msl12 replied at September 06, 2019 · 2615 hits

接触 ruby 没多久,在查看别人源码的时候,不明白它的实现原理

<td><%= impression.user&.name || impression.user&.nickname %></td>

是需要在 model.rb 里面定义什么吗?通过 &.name 这样就能取出这个 model 表中的名字了?求解答

Ruby 的 Safe Navigation Operator. 详见 https://ruby-china.org/topics/30415

好的,感谢

和 try(:name) 基本一致,不会因为 user 是 nil 而抛异常,而是返回一个 nil

Reply to w569893882

try 即使没方法也不会错,这个会

If you want to learn more, you can visit here https://github.com/ruby/ruby/blob/master/array.c.

[ 1, 1, 3, 5 ] & [ 3, 2, 1 ]                 #=> [ 1, 3 ]
[ 'a', 'b', 'b', 'z' ] & [ 'a', 'b', 'c' ]   #=> [ 'a', 'b' ]

Set Intersection — Returns a new array containing unique elements common to the two arrays. The order is preserved from the original array.

It compares elements using their hash and eql? methods for efficiency.

Reply to mizuhashi

平时没注意到,谢谢指出👍

不用就完事了

You need to Sign in before reply, if you don't have an account, please Sign up first.