I am trying to figure out how the '&' work in the below code?
:active is just an string
def current_subscription
subscriptions.find(&:active)
end
I am trying to figure out how the '&' work in the below code?
:active is just an string
def current_subscription
subscriptions.find(&:active)
end
Just remove the line breaks:
cats.each do |cat| cat.name end
Note, there are two different coding styles when it comes to blocks. One coding style says to always use do/end for blocks which span multiple lines and always use {/} for single-line blocks. If you follow that school, you should write
cats.each {|cat| cat.name }
The other style is to always use do/end for blocks which are primarily executed for their side-effects and {/} for blocks which are primarily executed for their return value. Since each throws away the return value of the block, it only makes sense to pass a block for its side-effects, so, if you follow that school, you should write it with do/end.
cats.each(&:name)
In this case it represents :active.to_proc
, which is short-form for:
subscriptions.find { |x| x.active }
You'll see the &:
notation frequently where it means roughly "call method with name on supplied object".
Remember :active
is not a String, it's a Symbol, or an "internalized" string. The difference is subtle but fundamental to Ruby. Symbols exist once and once only in Ruby, they're all identical, while strings can be duplicated but equivalent. In practice strings take more memory to store and more effort to compare which is why Symbols show up often in Hashes and as arguments to methods: They're efficient.