Reputation: 137
I'm trying to understand what's happening here in this short little snippet, but I'm not well versed in Ruby. Ultimately, what I'm trying to figure out is what's the difference between .path and [:path]?
if(hit.props && hit.props.path)
original_path = hit.props[:path]
I understand the if-statement part. Check if hit has props, and if it does check to see if it also has path in the props. I'm just confused as to what [:path] is trying to accomplish.
Upvotes: 0
Views: 48
Reputation: 165576
what's the difference between .path and [:path]
.path
is a method call. :path
creates a Symbol.
hit.props.path
calls the props
method on the hit
object. Then calls .path
on whatever is returned from that. It's equivalent to:
tmp = hit.props
tmp.path
hit.props[:path]
again calls the props
method on the hit
object. Then fetches the value from that (which is probably a Hash) the :path
key. :path
is a Symbol which is kind of like a read-only shared String. They're often used as hash keys to save a bit of memory and to make things look a bit neater.
It's equivalent to:
tmp = hit.props
val = tmp[:path]
While I said Symbols are similar to Strings, they are not Strings. tmp[:path]
and tmp["path"]
are not equivalent.
What your code is doing is checking that hit.props
and hit.props.path
exist before trying hit.props[:path]
. This is probably incorrect; hit.props.path
is not used.
You probably only want to check for hit.props
before trying to use it as a Hash.
if hit.props
original_path = hit.props[:path]
This can be further reduced using the Safe Navigation Operator &.
introduced in Ruby 2.3.
original_path = hit.props&.[](:path)
It works just like a normal method call, but if the object is nil
the call will return nil
rather than an error. If hit.props
is nil
then original_path
will be nil
. It DRYs up your code and eliminates redundant method calls; hit.props
is only called once.
Note that we're taking advantage of the fact that props[:path]
is really syntax sugar for calling the method []
on the props
object. A bit mind-bending, but all that's happening is it's a method with a weird name.
Upvotes: 3