Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
720 views
in Technique[技术] by (71.8m points)

iterator - Operator Precedence and Order of Evaluation in Ruby: yield vs << (shovel operator)

I'm reading this book Well-Grounded Rubyist and its Control-Flow Techniques chapter on p.184 has a simple example of implementing map with an iterator:

class Array
  def my_map
    c=0
    acc = []
    until c == size
      acc << yield self[c]
      c += 1 end
    acc
  end
end

I have the following error when run this code ruby MY_FILE.rb:

MY_FILE.rb:6: syntax error, unexpected `self', expecting `end'
      acc << yield self[c]

Solution to this problem is to put brackets around yield self[c], so this whole line would look like this:

  acc << (yield self[c])

Then, the routine works with this one-line change. In my understanding the problem is either with operator precedence or with order of evaluation. I surfed the web for quite a while but could not pinpoint why exactly the code from the book does not work.

Why the book example does not work? What is operator precedence or/and order of evaluation in acc << yield self[c]?

question from:https://stackoverflow.com/questions/65660677/operator-precedence-and-order-of-evaluation-in-ruby-yield-vs-shovel-operato

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Usually, method parameters come in parentheseis:

x=foo(y)
a=bar(baz(z))
b=7+baz(w)

In certain situations (i.e. if precedences does not bind otherwise), you can leave out the braces. Therefore,

x = foo y

works, but

a = bar baz z

is interpreted as

a = (bar(baz))(z)

and

b = 7 + baz w

as

b = (7+baz) w

This is risky, if the interpretation of the expression results in something meaningful. In this case, you would not even get an error message, but the program would simply behave in a different way than you expected.

In general, it is a good idea to always use parenthesis when invoking methods.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...