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

Allen_hui · 2019年09月03日 · 最后由 msl12 回复于 2019年09月06日 · 2616 次阅读

接触 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

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.

mizuhashi 回复

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

不用就完事了

需要 登录 后方可回复, 如果你还没有账号请 注册新账号