Ruby - how to assign multiple variables based on another boolean variable? - ruby

I am trying to do:
the_tag= line[2..5]
rec_id_line = (line[2]=='#')? true : false
new_contents,new_to_close=
rec_id_line? open_id_tag(indent,line) : open_tag(indent,the_tag,last_field)
Those two methods both return two values (btw I'm refactoring here)
i.e. for the two variables, I either want to call open_id_tag(2 params) otherwise open_tag(3 params) depending on the true/false rec_id_line value.

You just have to put a space between rec_id_line and ?:
new_contents, new_to_close = rec_id_line ? open_id_tag(indent, line) : open_tag(indent, the_tag, last_field)
Furthermore line[2]=='#' probably returns a boolean value so can simplify your second line:
rec_id_line = (line[2] == '#')
Or combine both lines:
new_contents, new_to_close = (line[2] == '#') ? open_id_tag(indent, line) : open_tag(indent, the_tag, last_field)

Related

'Return' outside of function

def suspect_dict():
dict = pd.read_csv("suspectdict.csv", squeeze=True)
pattern = '|'.join(dict)
result = np.where(news_df["headline"].str.contains(pattern, na=False),1, 0)
for index, value in enumerate(result):
return {value}
I am trying to return 1 and 0 if words in "suspectdict" exists in "news_df".
Code works for
for index, value in enumerate(result):
print(f"{value}")
example of output:
0
1
0
1
1
When using return I got Syntax error: 'return' outside function
How do I fix this?
As the error says, your return is outside a function. Return should be used within a scope of a function, in your case, on suspect_dict() function.
You could either just loop the result and print it, without returning anything, also, you don't need to use enumerate as you're not dealing with indexes:
def suspect_dict():
dict = pd.read_csv("suspectdict.csv", squeeze=True)
pattern = '|'.join(dict)
result = np.where(news_df["headline"].str.contains(pattern, na=False),1, 0)
for value in result:
print(value)
But if you need to return the result, you could just use return result inside the function:
def suspect_dict():
dict = pd.read_csv("suspectdict.csv", squeeze=True)
pattern = '|'.join(dict)
result = np.where(news_df["headline"].str.contains(pattern,na=False),1,0)
return result
Note that python uses indentation to understand where a block of code begins and ends, so make sure that all codes that might belong to the function are well indented.

How to alter Boolean value from true to false and vice-versa

I have a requirement in Go of altering the bool value and store it.
I am receiving value == true but I need to alter it and store the altered value.
I can think of only storing the alerted to a var and pass it in the next statement.
Eg psuedo code:
chnagevalue := false
if value == false {
changevalue == true
}
what's the best way to do it in Go? Is there any pre-defined way to do it?
Use the logical NOT operator ! to change true to false and vice versa:
changedValue := !value
There's a short answer, written somewhere else :-)
Yours is almost good too:
changedValue := false
if !value {
changedValue == true
}
An if statement is always about something being true.
so in the above it reads : if a value equals false is true then {}.
of course your mind reads it the short way :
if a value equals false then {}.
the switch of course works the best:
changedValue := !changedValue
BTW: I would never use a fieldname like "changedValue" because...
every variable is a value of some kind, so there is no need of writing that.
"changed" should be enough.
or, when it is a boolean like this , even better:
"isChanged" or "hasChanged"

Can I shortcut-check if a variable is `nil` and replace by a default value?

Is there a way to shortcut-check if a variable is nil, and give a default value if it is? For instance, replace
result = (var == nil ? defaultvalue : var)
with something like
result = selfifnotnil(var, default)
Of course I could write selfifnotnil function like the ternary above, but is there any built in option?
It's as simple as this (assuming that false and nil are treated the same)
result = var || defaultvalue
If false is a legitimate value (not a missing one), then you have to do that ternary.
result = var.nil? ? defaultvalue : var
Since nil is a falsely value. Therefore:
result = var || defaultvalue
Or if it is to check the var itself and assign default value. Also, if you are from another language, be careful which values are false in ruby.
result ||= default

more conventional way to write this ruby

this ruby code works, but is there a more conventional or simplified way to write it:
options['host'] = begin
a == :jaxon ? 'jaxon-server16.jaxon.local' : 'doric-server5'
end
I just feel like the code is a smell but I cannot put my finger on it.
Thanks.
You don't need begin..end here.
options['host'] = a == :jaxon ? 'jaxon-server16.jaxon.local' : 'doric-server5'
I'd probably put parentheses around right side. Not necessary, just for clarity.
options['host'] = (a == :jaxon ? 'jaxon-server16.jaxon.local' : 'doric-server5')
Usually symbols are used as hash keys because they save memory and are a little faster for comparisons, and the begin..end block is not necessary. Thus it becomes:
options[:host] = (a == :jaxon ? 'jaxon-server16.jaxon.local' : 'doric-server5')
This is a relatively long while, in my head the following parses easier:
options[:host] = 'doric-server5'
options[:host] = 'jaxon-server16.jaxon.local' if a == :jaxon
An iteration on top of that, is that you have what appears to be semi-hardcoded values (jaxon-server16.jaxon.local and doric-server5). You should store these in constants or another data structure in order to have these gathered in one place. For instance, if doric-server5 becomes doric-server6 one day, you'll only have to change it in the top of a class or file somewhere. Furthermore, it makes the code easier to read since they now have more humane names of whatever they represent.
# somewhere else:
JAXON_SERVER = 'jaxon-server16.jaxon.local'
DORIC_SERVER = 'doric-server5'
options[:host] = DORIC_SERVER
options[:host] = JAXON_SERVER if a == :jaxon
Since we've dealt with the original motivation to make it two lines, we could go back to one, nice line:
options[:host] = (a == :jaxon ? JAXON_SERVER : DORIC_SERVER)
If you have a lot of these kinds of statements, you could make a server hash, where e.g. server[:jaxon] = 'jaxon-server16.jaxon.local', but if you just have two, two string constants are fine.
In some cases it's nicer to have the default option (in this case DORIC_SERVER) appear wherever it would default to that value, instead of setting the host to the default value directly. Hash#fetch takes two arguments: a key, and a value to default to, if that key doesn't exist.
options[:host] = JAXON_SERVER if a == :jaxon
# somewhere else:
options.fetch(:host, DORIC_SERVER)
Without more information, it's hard to say which approach is the best in your case. :-)
This is another way to write it
options['host'] = case a
when :jaxon
'jaxon-server16.jaxon.local'
else
'doric-server5'
end
It has a lot more lines but i like its readability. It also makes it easy to add more hosts:
options['host'] = case a
when :jaxon
'jaxon-server16.jaxon.local'
when :staging
'staging-server1'
else
'doric-server5'
end
If you want to surround it with something for readability, you can share a pair of parentheses with the Hash#store method.
options.store( "host",
a == :jaxon ? "jaxon-server16.jaxon.local" : "doric-server5"
)

Using "? return :"

Below is part of a Ruby function that checks for a specific directory and creates it if it does not already exist:
if Dir.exists?(dir_name) == false
Dir.mkdir(dir_name)
end
I understand that there is a shorter way of doing the exact same thing:
Dir.exists?(dir_name) ? return : Dir.mkdir(dir_name)
However, I can't quite make sense of this. The important part of the second command is ? return :. The first part of the command has the parameter to check, and the last part has the action to take, but I can't make sense of ? return :. If I wanted the action in the last part of the command to execute if and only if dir_name did already exist, what would I use instead of ? return :?
You should use
Dir.mkdir(dir_name) unless Dir.exists?(dir_name)
unless <statement> is the same as if !<statement>. Remember never to make a statement that compares a boolean value to another boolean.
For example, increasing readability of your first statement
if Dir.exists?(dir_name) == false
if !Dir.exists?(dir_name)
unless Dir.exists?(dir_name)
The line Dir.exists?(dir_name) ? return : Dir.mkdir(dir_name) uses the ternary operator.
return immediately exits the function, usually returning a value like return "some value" but you can also just call return to exit the function and return nil.
Long story short the ternary version breaks the function if the dir exists, so nothing after that in the function would happen. So the equivalent is actually
Dir.exists?(dir_name) ? nil : Dir.mkdir(dir_name)
That is another way of writing an if-else.
Condition ? IfTrue : IfFalse
So,
Dir.exists?(dir_name) ? return : Dir.mkdir(dir_name)
Is the same as:
if Dir.exists?(dir_name)
return
else
Dir.mkdir(dir_name)
end

Resources