what does ? ? mean in ruby [duplicate] - ruby-on-rails

This question already has answers here:
How do I use the conditional operator (? :) in Ruby?
(7 answers)
Closed 7 years ago.
What does the line below checks and perform?
prefix = root_dir.nil? ? nil : File.join(root_dir, '/')
Here is the block that contains the line of code.
def some_name(root_dir = nil, environment = 'stage', branch)
prefix = root_dir.nil? ? nil : File.join(root_dir, '/')
.
.
.
i know that the '?' in ruby is something that checks the yes/no fulfillment. But I am not very clear on its usage/syntax in the above block of code.

Functions that end with ? in Ruby are functions that only return a boolean, that is, true, or false.
When you write a function that can only return true or false, you should end the function name with a question mark.
The example you gave shows a ternary statement, which is a one-line if-statement. .nil? is a boolean function that returns true if the value is nil and false if it is not. It first checks if the function is true, or false. Then performs an if/else to assign the value (if the .nil? function returns true, it gets nil as value, else it gets the File.join(root_dir, '/') as value.
It can be rewritten like so:
if root_dir.nil?
prefix = nil
else
prefix = File.join(root_dir, '/')
end

This is called a ternary operator and is used as a type of shorthands for if/else statements. It follows the following format
statement_to_evaluate ? true_results_do_this : else_do_this
A lot of times this will be used for very short or simple if/else statements. You will see this type of syntax is a bunch of different languages that are based on C.

The code is the equivalent of:
if root_dir.nil?
prefix = nil
else
prefix = File.join(root_dir, '/')
end
See a previous question

Related

Can a boolean be included in an "if" statement?

I'm just starting out on learning Lua (for 4 days now) and when running this code, I get an error: input:2: 'then' expected near '='
Here's the code I am using:
local imagineVar = true
if imagineVar = true then
print("LOL")
end
How do I fix this?
if imagineVar then
print("LOL")
end
in lua, anything in if statment will be true except false and nil
The error you're getting is a syntax error because assignments (var = something) are statements rather than expressions in Lua - that means they don't evaluate to a value and thus can't be used in an if-condition (or anywhere else where an expression is expected).
As others have pointed out, you'd use the operator == for comparison. It is however more idiomatic to check for truthiness if your variable is a boolean: if imagineVar then ... end; the body of the if will run only if imagineVar is not nil or false.
Compare needs double '='
local imagineVar = true
if imagineVar == true then
print("LOL")
end

Simple if else in rails

How to implement simple if else condition in rails
PHP : echo $params = isset($_POST['some_params']) ? $_POST['some_params'] : "";
RAILS : ??
Thanks,
You may want to look into Ruby Ternary operator: A good source is http://www.tutorialspoint.com/ruby/ruby_operators.htm
params[:some_params].present? ? 'a' : 'b'
another way of doing this is:
if params[:some_params].present?
....
else
....
end
There is one more operator called Ternary Operator. This first
evaluates an expression for a true or false value and then execute one
of the two given statements depending upon the result of the
evaluation. The conditional operator has this syntax:

How to Build regular expression pattern in rails

I am actually writing rails code where i want to check if
params[:name] = any character like = , / \
to return true or return false otherwise.
How do i build a regex pattern for this or if any other better way exists would help too .
sanitized = params[:name].scan(/[=,\/\\]/)
if sanitized.empty?
# No such character in params[:name]
else
# oops, found atleast 1
end
HTH
I don't know if it's achieved the status of "idiomatic", but I think the most compact way of achieving this in Ruby is with double !:
!!(params[:name] =~ /[=,\/\\]/)
as discussed in How to return a boolean value from a regex

LUA: Seeking efficient and error-free means of assigning default arguments

Instead of using long lists of arguments in my function definitions, I prefer to pass a few fixed parameters and a table of 'additional params' like this:
function:doit( text, params )
end
This is nice as it allows me to add new named parameters later without breaking old calls.
The problem I am experiencing occurs when I try to force default values for some of the params:
function:doit( text, params )
local font = params.font or native.systemBold
local fontSize = params.fontSize or 24
local emboss = params.emboss or true
-- ...
end
The above code works fine in all cases, except where I have passed in 'false' for emboss:
doit( "Test text", { fontSize = 32, emboss = false } )
The above code will result in emboss being set to true when I really wanted false.
To be clear, what I want is for the first non-NIL value to be assigned to emboss, instead I'm getting a first non-false and non-NIL.
To combat this problem I wrote a small piece of code to find the first non-NIL value in a table and to return that:
function firstNotNil( ... )
for i = 1, #arg do
local theArg = arg[i]
if(theArg ~= nil) then return theArg end
end
return nil
end
Using this function I would re-write the emboss assignment as follows:
local emboss = firstNotNil(params.emboss, true)
Now, this certainly works, but it seems so inefficient and over the top. I am hoping there is a more compact way of doing this.
Please note: I found this ruby construct which looked promising and I am hoping lua has something like it:
[c,b,a].detect { |i| i > 0 } -- Assign first non-zero in order: c,b,a
Lua's relational operators evaluate to the value of one of the operands (i.e. the value is not coerced to boolean) so you can get the equivalent of C's ternary operator by saying a and b or c. In your case, you want to use a if it's not nil and b otherwise, so a == nil and b or a:
local emboss = (params.emboss == nil) and true or params.emboss
Not as pretty as before, but you'd only need to do it for boolean parameters.
[snip - Lua code]
Now, this certainly works, but it seems so inefficient and over the top.
Please note: I found this ruby construct which looked promising and I am hoping lua has
something like it:
[c,b,a].detect { |i| i > 0 } -- Assign first non-zero in order: c,b,a
Your Lua function is no more over-the-top or inefficient. The Ruby construct is more succinct, in terms of source text, but the semantics are not really different from firstNotNil(c,b,a). Both constructs end up creating a list object, initialize it with a set of values, running that through a function that searches the list linearly.
In Lua you could skip the creation of the list object by using vararg expression with select:
function firstNotNil(...)
for i = 1, select('#',...) do
local theArg = select(i,...)
if theArg ~= nil then return theArg end
end
return nil
end
I am hoping there is a more compact way of doing this.
About the only way to do that would be to shorten the function name. ;)
If you really want to do it in a single line, you'll need something like this for a default value of true:
local emboss = params.emboss or (params.emboss == nil)
It's not very readable, but it works. (params.emboss == nil) evaluates to true when params.emboss is not set (when you would need a default value), otherwise it's false. So when params.emboss is false, the statement is false, and when it's true, the statement is true (true or false = true).
For a default of false, what you tried originally would work:
local emboss = params.emboss or false

Coffeescript ||= analogue?

I'm primarily a Rails developer, and so in whipping up a little script for my company's Hubot instance, I was hoping to accomplish the following:
robot.brain.data.contacts ||= {}
Or, only make this new hash if it doesn't already exist. The idea being that I want to have a contacts array added dynamically through the script so I don't have to modify Hubot's source, and I obviously don't want to overwrite any contacts I add to it.
Question: is there a quick little construct like the Rails ||= that I can use in Coffeescript to achieve the above goal?
Cheers.
You can use ?= for conditional assignment:
speed ?= 75
The ? is the "Existential Operator" in CoffeeScript, so it will test for existence (not truthiness):
if (typeof speed === "undefined" || speed === null) speed = 75;
The resulting JS is a bit different in your case, though, because you are testing an object property, not just a variable, so robot.brain.data.contacts ?= {} results in the following:
var _base, _ref;
if ((_ref = (_base = robot.brain.data).contacts) != null) {
_ref;
} else {
_base.contacts = {};
};
More info: http://jashkenas.github.com/coffee-script/
I personally use or= instead of ?= mainly because that's what I call ||= (or-equal) when I use it in Ruby.
robot.brain.data.contacts or= {}
The difference being that or= short-circuits when robot.brain.data.contacts is not null, whereas ?= tests for null and only sets robot.brain.data.contacts to {} if not null.
See the compiled difference.
As mentioned in another post, neither method checks for the existence of robot, robot.brain or robot.brain.data, but neither does the Ruby equivalent.
Edit:
Also, in CoffeeScript or= and ||= compile to the same JS.
?= will assign a variable if it's null or undefined.
Use it like speed ?= 25
It's called the existential operator in Coffeescript and is ?=, http://coffeescript.org/. Quoting below:
The Existential Operator
It's a little difficult to check for the existence of a variable in
JavaScript. if (variable) comes close, but fails for zero, the empty
string, and false. CoffeeScript's existential operator ? returns true
unless a variable is null or undefined, which makes it analogous to
Ruby's nil?
It can also be used for safer conditional assignment than ||=
provides, for cases where you may be handling numbers or strings.
The Coco dialect of CoffeeScript, http://github.com/satyr/coco , supports the array and object autovivification operators # and ##:
robot#brain#data#contacts.foo = 1
compiles to - granted, hairy-looking -
var _ref, _ref2;
((_ref = (_ref2 = robot.brain || (robot.brain = {})).data || (_ref2.data = {})).contacts || (_ref.contacts = {})).foo = 1;
which ensures that each step of the way, robot.brain, brain.data, data.contacts actually exists.
Of course you might just want the actual conditional assignment operator (which, according to the above answers, also exists in CoffeeScript):
robot.brain.data.contacts ?= {}
that compiles to
var _ref;
(_ref = robot.brain.data).contacts == null && (_ref.contacts = {});
a ||= b means if a exists, do nothing. If a doesn't exist, make it equal to b.
Example1:
a = undefined;
console.log(a ||= "some_string") //prints some_string
Example2:
a = 10
console.log(a ||= "some_string") //prints 10

Resources