I am very new to Ruby, so please accept my apologies if this question is wierd
I tried puts 5-8.abs which returned -3, and then I tried puts (5-8).abs which returned 3.
What is happening exactly when I try puts 5-8.abs, it seems like abs is ignored?
It's a precedence issue. The method call, .abs, is evaluated before the minus operator.
5-8.abs # => equivalent to 5-(8.abs)
Think of it this way - whitespace is not significant in Ruby. What would you expect to happen if you saw this?
5 - 8.abs
Here's a reference for Ruby precedence rules.
Method call (8.abs in this case)always has higher Precedence than operators (- in this case).
So, 5-8.abs translats to 5-(8.abs) = 5 - 8 = -3
5-8.abs seems to be doing 5-(8.abs) = 5-8 = -3 like you got.
Also, any time precedence is the least bit up in the air, explicit parenthesization helps.
Related
I am sure that this has been asked, but I can't find it through my rudimentary searches.
Is it discouraged to perform operations within string initializations?
> increment = 4
=> 4
> "Incremented from #{increment} to #{increment += 1}"
=> "Incremented from 4 to 5"
I sure wouldn't, because that's not where you look for things-that-change-things when reading code.
It obfuscates intent, it obscures meaning.
Compare:
url = "#{BASE_URL}/#{++request_sequence}"
with:
request_sequence += 1
url = "#{BASE_URL}/#{request_sequence}"
If you're looking to see where the sequence number is coming from, which is more obvious?
I can almost live with the first version, but I'd be likely to opt for the latter. I might also do this instead:
url = build_url(++request_sequence)
In your particular case, it might be okay, but the problem is that the position where the operation on the variable should happen must be the last instance of the same variable in the string, and you cannot always be sure about that. For example, suppose (for some stylistic reason), you want to write
"Incremented to #{...} from #{...}"
Then, all of a sudden, you cannot do what you did. So doing operation during interpolation is highly dependent on the particular phrasing in the string, and that decreases maintainability of the code.
I want to write a tiny DSL in ruby for simple arithmetic. It would look something like this:
whats 1 + 1
=> 2
whats 2 * 2
=> 4
The use case is teaching my child to program. I was showing her basic programming with irb, and when I gave her the keyboard she typed "whats 2 + 2" - possible in ruby?
Actually, it's quite simple:
def whats expr; expr end
whats 1 + 1
# => 2
What you want can’t be done all that elegantly because of Ruby’s operator precedence. In other words, because whats 1 + 1 is the same as whats(1 + 1) (and whats(2)), the whats method has no idea that an operation occurred in its arguments.
You’ll have to override Fixnum#+ (and any other operators) to return some sort of builder object. For example:
MathQuery = Struct.new(:left, :operator, :right)
class Fixnum
def + other
MathQuery.new(self, :+, other)
end
end
Then 1 + 1 would return a MathQuery instance, which whats would receive and know how to handle.
Of course, the problem with this is that you’d need to somehow also make normal math operations still work, since lots of code obviously expects them to. Not quite sure how to pull that off, though. Maybe if everything always coerced with to_int, etc.…
In which case you might be better off writing an actual mini-language and parser using something like Treetop.
Write a method called 'whats', accept any number of arguments, match the operator portion(s), and proceed.
I'm doing API calls that will conditionally return a couple different elements. My code is currently:
if array['productId']
value = array['productId'][0]
end
I feel like there is a more succinct way of doing this. Some Ruby magic.
A better way :
value = array['productId'][0] if array['productId']
However, array['productId'][0] is not ruby natural. What does your array consist of ?
Since Ruby 2.3.0, the shortest way is Array#dig:
array.dig('productId', 0)
http://ruby-doc.org/core-2.3.0_preview1/Array.html#method-i-dig
I am not sure if you are using value just temporarily or actually using it later, and what you want to do with value when the condition is not met. If you want to return nil for missing keys, then
array['productId'].to_a[0]
can work. Otherwise, SpyrosP's answer will be the best.
This might be a bit pedantic, but to make sure it works in all circumstances, you should not check 'not-nil', but rather that it is indexable; something like this:
value = array['productId'][0] if array['productId'].is_a? Array
Or even better:
value = array['productId'][0] if array['productId'].respond_to? '[]'
Otherwise your code will fail if array['productId'] == 2 (which on the other hand seems reasonable, given the key used - I would have gone product_ids instead).
You could use a ternary:
value = array['productId'].nil? ? nil : array['productId'][0]
Your code pattern looks OK; it's possible to be slightly shorter...
value = (t = x['productId']) && t[0]
Using the maybe pattern of Ick, terse and explicit:
value = array['productId'].maybe[0]
While I think your code is fine (although I'd prefer SpyrosP's one-line version), you have some possibilities:
Rails has Object#try, which would let you do either array['productId'].try(:[], 0) or array['productId'].try(:at, 0).
Some people like the andand gem, which defines Object#andand and is used like array['productId'].andand[0].
Ha, I love all the options here. But since I didn't see what I use most, I'll add one more!
value = array['productId'] && array['productId'].first
(I prefer .first to [0] because it reads a little better)
This presumes you'll have an array in array['productId'], which is the right way to do it (rather than type-checking).
Otherwise, the biggest diference between this and your original code, is that this results in value having nil assigned to it if the array doesn't have anything, whereas your original results in value not being defined (which may cause errors, depending on how you use it down the road).
Hope that helps!
I remember seeing a recipe to take an expression and evaluate every Head that matches pattern x, while leaving subexpressions with non-matching heads unevaluated. I can't find this recipe anymore, does anyone know the right way to do this?
This one is from Ted Ersek's Mathematica Tricks under "Clever Little Programs".
Thanks to #TomD for the pointer.
EvaluatePattern[expr_,pattn_]:=expr/.Pattern[p, pattn]:>With[{eval=p},eval/;True]
In[368]:= test = HoldForm[7 (1 + 2 - 2^2) (8 + 8)];
EvaluatePattern[test, _Plus] //InputForm
Out[369]= HoldForm[7*-1*16]
Edit
It seems to work also with Hold[], but I never ran a deep test.
Just tried to execute a small Lua script, but unfortunately I'm doing something wrong. I've no more ideas what the fault might be.
function checkPrime( n )
for i = 2, n-1, 1 do
if n % i == 0 then
return false
end
end
return true
end
The interpreter says:
lua: /home/sebastian/luatest/test.lua:3: `then' expected near `%'
I think it's not a big thing and perhaps it's quite clear what is wrong. But somehow I cannot see it at the moment.
There is probably some version problem, check your version of lua. The usage of '%' as an infix operator for modulo can only be used in Lua 5.1, in 5.0 it is not supported yet. Try using math.mod instead:
if math.mod(n,i) == 0 then
Edit: Also note that in 5.1, math.mod still exists, but it has been renamed to math.fmod. For now, the old name still works, but support will probably be removed in future versions.
Have you tried wrapping "n% i == 0" in parentheses? Stupid question, but sometimes overlooked!