I need to make my code more compact. I have the following code:
params[:investor][:profit] = params[:investor][:profit].nil? ? nil : params[:investor][:profit].gsub(/\D/, '')
Basically what it does - it formats profit value from params to contain only digits, and if it was nil - just keep it nil...Is there any way to make it shorter.
You could tighten it down a little bit like so:
params[:investor][:profit].gsub!(/\D/, '') unless params[:investor][:profit].nil?
You could use the #try method from active_support:
params[:investor][:profit].try(:gsub!, /\D/, '')
um
p = params[:investor][:profit]
p = p.nil? ? nil : p.gsub(/\D/,'')
params[:investor][:profit] &&= params[:investor][:profit].gsub(/\D/, '')
If the value of params[:investor][:profit] is nil, this will evaluate to nil && .... Since nil is false, it will stay at nil, otherwise do the gsub.
I think it is heads up with the try solution mentioned in another solution. Choosing one over the other comes down to personal taste. I like the &&= solution because it's ruby instead of a rails convenience method and you do not need to "encrypt" what you really want to do in the try method's parameters.
params[:investor][:profit].gsub!(/\D/, '') if params[:investor][:profit]
or what I almost always use:
params[:investor][:profit].gsub!(/\D/, '') rescue nil
prof = params[:investor][:profit]
prof.gsub!(/\D/,'') if prof
Related
I would like to prepend a '/' if the variable follow has a value otherwise if it is nil then keep it as nil
l2, follow = params[:all].split('/', 2)
follow = follow.nil? ? follow : "/#{follow}"
redirect_to "#{my_path(locale: locale, l2: l2)}#{rest}"
the params[:all] here could be a url path like
esp
esp/article/1
esp/article/1/author/1
EDIT:
My approach works but would like to know if there is a better way
follow.nil? ? follow : "/#{follow}"
Since Ruby has String#prepend method, the code can be refactored the following way:
follow && follow.prepend("/")
Or since Ruby 2.3 has safe navigation, it can be expressed even more concise:
follow&.prepend("/")
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
In the process of learning ruby (I have a java background).
I have assignment statements where the value of one hash[:name_field] is being assigned to another. But the value coming from the hash on the right was sometimes blank. This was crashing my code hence i added the ternary logic with .nil ? etc....
I am surprised though that this doesn't work... The error is :
undefined method `nil' for 1133:Fixnum (NoMethodError)
Below is the code:
people_traffic.each do |person|
person_record = DaysTraffic.new
person_record[:name] = person[:name_filed].nil ? 0 : person[:name_filed]
person_record[:age] = person[:age_field].nil ? 0 : person[:age_field]
person_record.save
end
Why am I getting the (NoMethodError) for the nil?
Thank you!
It should be .nil? (with a question mark) not .nil. So in your case, that would be:
person_record[:name] = person[:name_filed].nil? ? 0 : person[:name_filed]
You can actually write this much simpler like so:
person_record[:name] = person[:name_filed] || 0
Because #to_i turns nil into 0, a good way to write something like this is:
person_record[:age] = person[:age_field].to_i
I have this simple condition in my ruby code:
if user.text != ("Empty" || "Damaged")
do something...
the thing is that when it is "Damaged" it still enters the loop, so I have to use this:
if user.text != "Empty"
if user.text != "Damaged"
...
..
What is the correct syntax to make the first one work?
Thanks!
Use this:
unless ["Empty", "Damaged"].include?(user.text)
...
end
The problem with your first approach is that a || b means that: if a != nil then it is a, else it is b. As you can see it is good for variables, not constants as they are rarely nil. Your expression ("Empty" || "Damaged") simply equals "Empty".
You want to use the this as a binary operator, the correct form would be:
if (user.text != "Empty") && (user.text != "Damaged")
The upper solution is just shorter. It consists of an array of elements you want to avoid, and you just simply check is the user.text is not present in it.
#Matzi has the right answer, for sure. But here's why what you're doing is failing:
Your statement ("Empty" || "Damaged") evaluates to "Empty"
You're saying return either one of these, whichever non-false thing you find first. In Ruby, any string, number or Object returns true, so you return "Empty" every time.
A better way to lay it out if you really want to use an if statement:
if user.text != "Empty" && user.text != "Damaged"
...
end
I assume, by the way, that you're trying to say "If the user text is neither Damaged nor Empty".
Hope that helps.
if ((text != "Empty") && (text != "Damaged"))
I'm trying to create a BBcode [code] tag for my rails forum, and I have a problem with the expression:
param_string.gsub!( /\[code\](.*?)\[\/code\]/im, '<pre>\1</pre>' )
How do I get what the regex match returns (the text inbetween the [code][/code] tags), and escape all the html and some other characters in it?
I've tried this:
param_string.gsub!( /\[code\](.*?)\[\/code\]/im, '<pre>' + my_escape_function('\1') + '</pre>' )
but it didn't work. It just passes "\1" as a string to the function.
You should take care of the greedy behavior of the regular expressions. So the correct code looks like this:
html.gsub!(/\[(\S*?)\](.*?)\[\/\1\]/) { |m| escape_method($1, $2) }
The escape_method then looks like this:
def escape_method( type, string )
case type.downcase
when 'code'
"<pre>#{string}</pre>"
when 'bold'
"<b>#{string}</b>"
else
string
end
end
Someone here posted an answer, but they've deleted it.
I've tried their suggestion, and made it work with a small change. Whoever you are, thanks! :)
Here it is
param_string.gsub!( /\[code\](.*?)\[\/code\]/im ) {|s| '<pre>' + my_escape_function(s) + '</pre>' }
You can simply use "<pre>#{$1}</pre>" for your replacement value.