Ruby - incorrect line break within statement still gives result? - ruby

The distilled script is the following:
z1 = (12 -
2) / (5)
z2 = (12
- 2) / (5)
puts(z1.to_s + " " + z2.to_s)
Which gives:
$ ruby rubytest.rb
2 -1
Now, I'm aware that the z1 case is the right way to do it, because a hanging operator on the end of the line is interpreted as an automatic continuation of the line.
However, I would expect the interpreter to fail-fast on the z2 case, and tell me that the statement is incomplete, or that its second line is nonsensical. But it handles it "just fine" and gives the "-1" answer. Is it trying to appear confident by not admitting it's confused and hoping the bullshit answer will go unnoticed?
Could someone explain what is actually happening with the evaluation of z2, why is it "-1", why is there no syntax error, and is there an example where this behaviour is useful (or should we file a request to remove it)?

It's a feature, but you might think it's a bug at first. It's for the same reason you are able to do this (which is handy many cases):
(call_function_1; call_function_2) if some_condition
A line feed is interpreted the same as ;. You will notice this evaluates fine for example, and only the last expression is returned, but all expression ARE evaluated none the less:
(1
2
3
4
5)
=> 5
It's the same as
(1; 2; 3; 4; 5)
=> 5
To see that all expressions are evaluated you can try this for example:
(puts "A"
puts "B"
puts "C"
123)
A
B
C
=> 123
So your example becomes:
(12; -2) / 5
Which is the same as:
-2 / 5
Which is -1.
To make Ruby interpret 12 as an unfinished statement and not a separate statement you can tell Ruby this by adding a line continuation hint \:
(12 \
- 2) / 5
=> 2

Related

How to fix " '=' expected near '. .' " error in Lua

This error occurs on line 3 of my code and I don't know why.
I'm trying to create multiple variables with x..q, but it doesn't work.
for i=1,3 do
for q=1,3 do
x..q=i+1
print(x..q)
end
end
The output should be:
2
2
2
3
3
3
4
4
4
But instead it returns the error in the title.
If you want to create multiple global variables, use code like this:
for i=1,3 do
for q=1,3 do
_G["x"..q]=i+1
print(_G["x"..q])
end
end
This code will create globals x1, x2, and x3.
But I think you'd be better off using a table:
x={}
for i=1,3 do
for q=1,3 do
x[q]=i+1
print(x[q])
end
end
I believe you are using the operator .. unintentionally.
When accessing a value of a table, the syntax is x.q. Programming in Lua: 2.5 – Tables
To represent records, you use the field name as an index. Lua supports this representation by providing a.name as syntactic sugar for a["name"]. So, we could write the last lines of the previous example in a cleanlier manner as
a.x = 10 -- same as a["x"] = 10
print(a.x) -- same as print(a["x"])
print(a.y) -- same as print(a["y"])
When concatenating a string the syntax is x .. q.
Programming in Lua: 3.4 – Concatenation
Lua denotes the string concatenation operator by ".." (two dots). If any of its operands is a number, Lua converts that number to a string.
print("Hello " .. "World") --> Hello World
print(0 .. 1) --> 01

[] reduce with anonymous function in Perl 6

We can use reduce with a sub with two arguments, putting it in double brackets:
> sub mysum { $^a + $^b }
> [[&mysum]] 1,3,5
9
But what if we want to use an anonymous function instead?
Both following variants produce a compile error:
> [[&{ $^a + $^b }]] 1,3,5
> [[{ $^a + $^b }]] 1,3,5
You are not allowed to have any spaces in that form of reduce.
> [[&({$^a+$^b})]] 1, 3, 5
9
This is so that it is more obvious that it is a reduce, and not an array declaration.
> [ { $^a + $^b }, { $^a * $^b } ].pick.(3,5)
8 | 15
The double [[…]] is just an extension of allowing any function to be used as an infix operator.
Note that you must use &(…) in this feature, when not talking about a named function &foo, or an already existing infix operator.
> 3 [&( { $^a + $^b } )] 5
8
This is sort-of an extension of using […] for bracketing meta operators like Z and =
> #a [Z[[+]=]] 1..5
> #a Z[[+]=] 1..5
> #a Z[+=] 1..5
> #a Z+= 1..5
Not sure why that doesn't work. But there's always:
say reduce { $^a + $^b }, 1,3,5 # 9
I'm guessing you knew that but it's all I've got for tonight. :)
I've now moved my comment here and expanded it a bit before I go to sleep.
The TTIAR error means it fails to parse the reduce as a reduce. So I decided to take a quick gander at the Perl 6 grammar.
I searched for "reduce" and quickly deduced that it must be failing to match this regex.
While that regex might be only 20 or so lines long, and I recognize most of the constructs, it's clearly not trivial. I imagine there's a way to use Grammar::Debugger and/or some other grammar debugging tool with the Perl 6 grammar but I don't know it. In the meantime, you must be a bit of a regex whiz by now, so you tell me: why doesn't it match? :)
Update
With Brad's answer to your question as our guide, the answer to my question is instantly obvious. The first line of the regex proper (after the two variable declarations) directly corresponds to the "no spaces" rule that Brad revealed:
<?before '['\S+']'>
This is an assertion that the regex engine is positioned immediately before a string that's of the form [...] where the ... is one or more non-space characters. (\s means space, \S means non-space.)
(Of course, I'd have been utterly baffled why this non-space rule was there without Brad's answer.)

Write Multiline Arithmetic in Ruby

How to write multiline arithmetic properly in Ruby? Previously, i have tried something like y, then i realized there is something wrong with that code. I need to write multiline arithmetic due to my very long equation.
a = 5
b = 5
x = (a + b) / 2
puts x # 5, as expected
y = (
a
+ b
) /
2
puts y # 2, what happened?
The Ruby parser will assume a statement has ended if it looks like it has ended at an end of the line.
What you can to do prevent that is to leave the arithmetic operator just before a new line, like this:
a = 1
b = 2
c = a +
b
And you'll get the result you expect.
(
expr1
expr2
)
is actually, in Ruby, the same as
(expr1; expr2)
which just executes the first expression (for side effects) and returns the second one (also after evaluating it)
Try thinking about the "expectations" of the interpreter, and remember that in ruby EVERYTHING is an expression (which means that everything evaluates to some value, even constructs that in other languages are considered "special", like if-then-elses, loops, etcettera).
So:
y = ( #1
a #2
+ b #3
) / #4
2 #5
At line 1 we start the declaration of a variable, and the line ends with an open (pending) parenthesis. The interpreter expects the rest of the definition, so it proceeds to the next line looking for a VALUE to assign to the var y.
At line 2, the interpreter finds the variable a, but no enclosing parenthesis. It evaluates a, which has value 5, and since the line 2 is a perfectly-valid expression, the interpreter understands that this expression is finished (since in Ruby a newline OFTEN means end-of-expression indicator).
So up to now it has produced a value 5, but the only expectation it still has is that it must match the enclosing parenthesis.
If after that the interpreter had found the enclosing parenthesis, it would have assigned the value of a (i.e. 5) to the parenthesis expression (because everything must have a value, and the last value produced will be used).
When the interpreter reaches line 3, it finds another perfectly-valid ruby expression, + b. Since + 5 (5 being the value of variable b) is a VALID integer declaration in ruby, the interpreter sees it as standalone, not at all related to the previous 5 evaluated for the variable a (remember, it had no other expectation, except the one for the parenthesis).
In short, it throws away the value obtained for a, and uses only the value obtained with + b. In the next line it finds the enclosing parenthesis, and so the parenthesis-expression gets assigned the last produced value, which is a 5 produced by the expression + b.
Since on line 4 the interpreter finds a /, it (correctly) understands it as the division method of an integer, since it has produced an integer up to now (the int 5)! This creates the expectation for possible arguments of the method, which it finds on line 5. The resulting evaluated expression is y = 5 / 2, which equals 2 in integer division. So, basicaly, here is what the interpreter did:
y = ( # Ok, i'm waiting for the rest of the parenthesis expression
a # cool, a has value 5, if the parenthesis ends here, this is the value of the expr.
+ b # Oh, but now I found + b, which has value + 5, which evaluates to 5. So now this is the last value I have evaluated.
) / # Ok, the parenthesis have been closed, and the last value I had was a 5. Uow, wait, there is a slash / there! I should now wait for another argument for the / method of the 5 I have!
2 # Found, let's make y = 5 / 2 = 2!
The problem here is that on line #2, you should have left an expectation for the interpreter (exactly as you left on line 4 with the / method), which you did not!
The answer of #Maurício Linhares suggests exactly this:
y = (
a +
b
) /
2
By moving the + method to the end of the line 2, you tell the interpreter that your expression is still not complete! So it keeps the expectation and proceeds to line #3 to find the right operand of the expression (or, more precisely in Ruby, an argument for the + method :D).
The same works with string concatenation:
# WRONG, SINCE + "somestring" is not a valid stand-alone expression in ruby
str = "I like to"
+ " move it!"
# NoMethodError: undefined method `+#' for " move it!":String
# CORRECT, by leaving the + sign as last statement of the first line, you
# keep the 'expectation' of the interpreter for the next
# argument of the + method of the string object "I like to"
str = "I like to" +
" move it!"
# => "I like to move it!"
The difference is that in your code there were no error thrown, since + b is actually a valid expression.
I hope my answer was useful on giving you some intuition on WHY it was not working as expected, sorry if I'm not concise :)

Ruby operator "+" behavior varies depending on spacing in code?

I came across a bit of an oddity (am using Ruby 1.9.1). Case scenario being:
class D
...
def self.d6
1+rand(6)
end
...
end
v = D::d6+2 # fine and dandy
v = D::d6 +2 # in `d6': wrong number of arguments (1 for 0) (ArgumentError)
v = D::d6 + 2 # fine and dandy
Why the "+2" in second case is treated as being "positive 2" and not an "addition of 2"?
The + same as the - in ruby are overloaded in order to make the syntax look nice.
When there is no space the Ruby parser recognizes the + as the method which is called on the result of d6 which is an Integer.
Same goes for the version with space before and after the +.
However: In the operator precedence in Ruby + as a unary operator is defined before + as a binary operator (as is often the case in other languages as well).
Therefore if there is a space before the + but not after it, the Ruby Parser will recognize it as d6(+2) which fits the error message.

Ruby Parenthesis syntax exception with i++ ++i

Why does this throw a syntax error? I would expect it to be the other way around...
>> foo = 5
>> foo = foo++ + ++foo
=> 10 // also I would expect 12...
>> foo = (foo++) + (++foo)
SyntaxError: <main>:74: syntax error, unexpected ')'
foo = (foo++) + (++foo)
^
<main>:75: syntax error, unexpected keyword_end, expecting ')'
Tried it with tryruby.org which uses Ruby 1.9.2.
In C# (.NET 3.5) this works fine and it yields another result:
var num = 5;
var foo = num;
foo = (foo++) + (++foo);
System.Diagnostics.Debug.WriteLine(foo); // 12
I guess this is a question of operator priority? Can anybody explain?
For completeness...
C returns 10
Java returns 12
There's no ++ operator in Ruby. Ruby is taking your foo++ + ++foo and taking the first of those plus signs as a binary addition operator, and the rest as unary positive operators on the second foo.
So you are asking Ruby to add 5 and (plus plus plus plus) 5, which is 5, hence the result of 10.
When you add the parentheses, Ruby is looking for a second operand (for the binary addition) before the first closing parenthesis, and complaining because it doesn't find one.
Where did you get the idea that Ruby supported a C-style ++ operator to begin with? Throw that book away.
Ruby does not support this syntax. Use i+=1 instead.
As #Dylan mentioned, Ruby is reading your code as foo + (+(+(+(+foo)))). Basically it's reading all the + signs (after the first one) as marking the integer positive.
Ruby does not have a ++ operator. In your example it just adds the second foo, "consuming" one plus, and treats the other ones as unary + operators.

Resources