Skip to content

Instantly share code, notes, and snippets.

@DFrenkel
Created April 4, 2014 22:58
Show Gist options
  • Save DFrenkel/9984682 to your computer and use it in GitHub Desktop.
Save DFrenkel/9984682 to your computer and use it in GitHub Desktop.
b && c in ruby
[true, false, 1223, nil].each do |b|
[true, false, 5555, nil].each do |c|
a = b && c
puts "#{b} && #{c} = #{a}"
end
end
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
true && true = true
true && false = false
true && 5555 = 5555
true && =
false && true = false
false && false = false
false && 5555 = false
false && = false
1223 && true = true
1223 && false = false
1223 && 5555 = 5555
1223 && =
&& true =
&& false =
&& 5555 =
&& =
@frightenedmonkey
Copy link

For what it's worth, the context I saw it in was:
some_id = params[:foo] && params[:foo][:bar_id]
...
SomeModel.find_by_id(some_id)

which is equivalent to:
some_id = params[:foo][:bar_id] if params[:foo]

In this particular case, the usage was, only assign to the variable if the hash exists. And then go use whatever that value was somewhere else. On reading it, I thought that line -- some_id = params[:foo] && params[:foo][:bar_id] --
was assigning a boolean to some_id, and so was confused by the later usage. Maybe it's common elsewhere, but I haven't seen it before.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment