Ruby - unexpected behaviour when using &&

When I write the following line:

if (collection.respond_to? :each && collection.respond_to? :to_ary)

my IDE (Aptana Studio 3) gives me the following error: , unexpected tSYMBEG

however the error goes away if I add brackets:

if ((collection.respond_to? :each) && (collection.respond_to? :to_ary))

or change && to and:

if (collection.respond_to? :each and collection.respond_to? :to_ary)

Any ideas why this is happening? Also what is the difference between && and and?


-------------Problems Reply------------

&& has a high precedence (stronger than and, stronger than =).

foo = 3 and 5 # sets foo = 3
foo = 3 && 5 # sets foo = true

It's also stronger than an ambiguous function call. Your code is parsed as such

if (collection.respond_to? :each && collection.respond_to? :to_ary)
if (collection.respond_to? (:each && collection.respond_to?) :to_ary)

which doesn't make any sense. While using and is parsed as such

if (collection.respond_to? :each and collection.respond_to? :to_ary)
if (collection.respond_to?(:each) and collection.respond_to?(:to_ary))

I recommend that you use this one (as it doesn't rely on operator precedence rules and uses the least braces, has shortest brace-distances, and uses and which are more often to be found in if conditions than &&):

if collection.respond_to?(:each) and collection.respond_to?(:to_ary)

Because Ruby is a dynamic language ruby has no way of knowing if you are using the symbols as integers (in which the are stored), and thus the '&&' operator has precedens over function calls, thus you are actually calling

collection.respond_to? (:each && collection.respond_to? :to_ary) instead of calling

(collection.respond_to? :each) and (collection.respond_to? :to_ary)

which is to method calls then an boolean logic operator. When using 'and' instead of &&, 'and' has much lower precedens (lower than function calls) and thus it also works.

'and' and 'or' vs '&&' '||'

Category:ruby Views:0 Time:2011-04-03
Tags: ruby ruby 1.9

Related post

  • Unexpected behaviour of function findpeaks in MATLAB's Signal Processing Toolbox 2010-12-07

    Edit: Actually this is not unexpected behaviour, but I still need a solution. findpeaks compares each element of data to its neighboring values. I have data which contains peaks which I detect with the function findpeaks from the Signal Processing To

  • Flex Binding : Unexpected behaviour 2011-05-04

    I have noticed an unexpected behaviour with binding in Flex, my code is as follow : Application code <mx:Application xmlns:mx="" layout="vertical" horizontalAlign="center" xmlns:Model="Model.*"> <mx:Script>

  • Unexpected behaviour while using sprintf() and sscanf() in c++? 2011-11-14

    i have formated a string using sprintf() as follows: int wValue = 1; ostringstream ossi1; ossi1 << "messageContent"; std::string orinal = "this is la large string \n containin large content separated \n by newline character" char buff[50000] =

  • Position:absolute within floated list of elements: unexpected behaviour 2011-12-21

    I was working on a jsfiddle in an attempt to provide an answer to this question, but ran into some unexpected behaviour. I have a list of floated boxes (float:left), flowing over multiple lines. If I add position:absolute to a box on the first line,

  • Something seems wrong with the layout, JButton showing unexpected behaviour at resize of the window 2012-03-24

    JRE Version 1.7 Update 3 EXPECTED BEHAVIOUR As I run the program, it works as expected, everything works smoothly. As when I click on STOP JButton the animation stops and the text on the same JButton changes to START. Now when i click on BALL COLOUR

  • json parse error in ruby - unexpected token at 2010-02-26

    I get errors at a lot of places when trying to retrieve ticker symbols for US companies from I have tried to: resp = Net::HTTP.get_resp

  • Unexpected behaviour with Python urllib 2010-12-12

    I am tryint to consume a JSON response but I have one very weird behaviour. The end point is a Java app running on Tomcat. I want to load the following url Using R

  • Unexpected behaviour of virtual function? 2011-07-12

    When I run following C++ code with Visual Studio 2010, the program stucks at the deletion of variable if any of the derived class function is declared as virtual. Can someone explain it? void testInheritance() { class a { public : char x; void fn1()

  • iscroll4 unexpected behaviour in firefox 2011-12-27

    I am using iscroll 4 from and this is working good for me but i am facing one unusual behaviour. I have set up the demo in . Please check in both chrome and firefox. The mouse move is working smoo

  • why unexpected behaviour for conditional operator 2012-01-17

    I have a piece of code like follows public class Test{ public static void main(String[] args) { System.out.println(true?false:true == true?false:true); ----------------------- } } The output is false. If you are using Eclipse you get a wavy (dashed h

  • Ruby: unexpected semicolon in block parameters 2012-01-22

    I just started learning Ruby. I typed the example: x = 10 5.times do |y; x| x = y puts "x inside the block: #{x}" end puts "x outside the block: #{x}" And I have an error: hello.rb:3: syntax error, unexpected ';', expecting '|' 5.times do |y; x| Expl

  • Ruby: Unexpected Results from class_exec When Defining Class Variable 2012-04-11

    In Ruby, when defining the contents of a class with class_exec, I am getting unexpected results. When I define a class variable in the block sent to class_exec, the class variable is being defined on Object instead of the class on which class_exec is

  • Django choice field unexpected behaviour (bug?) 2014-12-01

    I came across some weird behaviour in the migrations with Django 1.7. Is this a legitimate bug that should be reported? In summary: I used a module level CHOICE field, which I initially referenced in one Model class. Next I made some alterations and

  • Unexpected behaviour of Process.MainWindowHandle 2008-09-07

    I've been trying to understand Process.MainWindowHandle. According to MSDN; "The main window is the window that is created when the process is started. After initialization, other windows may be opened, including the Modal and TopLevel windows, but t

  • Cycling through array of objects within view in Rails: unexpected behaviour 2009-01-30

    I've got a simple calendar displaying some events, that's not quite giving me the expected results. Here's the code: <!-- Begin Calendar --> <%= calendar(:year => @year, :month => @month, :first_day_of_week => 1) do |d| output = []

  • cursor loop and continue statement : unexpected behaviour 2009-06-09

    I might be overlooking something due to deadline stress. But this behaviour amazes me. It looks as if the cursor caches 100 rows and the continue statement flushes the cache and begins with the first record of a new cache fetch. I narrowed it down to

  • Regex/lastIndex - Unexpected behaviour 2009-10-07

    I know there are a few regex/lastIndex discrepancies but this one is new to me! Expected behaviour: Creating a new regular expression (with literal/constructor) will, obviously, create a new RegExp object with a lastIndex property set to zero. Actual

  • C++ functor - unexpected behaviour? 2009-10-16

    I have written this program, which sorts some ints using a functor: #include<iostream> #include<list> #include<set> using namespace std; struct IntSorter { unsigned int comparisons; IntSorter() { std::cout << "new intsorter"

  • sql server 2005 stored procedure unexpected behaviour 2010-03-27

    i have written a simple stored procedure (run as job) that checks user subscribe keyword alerts. when article posted the stored procedure sends email to those users if the subscribed keyword matched with article title. One section of my stored proced

Copyright (C), All Rights Reserved.

processed in 0.091 (s). 11 q(s)