The following code won't change the variable:
#my_var = ''
#my_var ||= 'This is a non-empty string'
Is there any nice/clean way to do this so that empty strings are overwritten?
you can try like this:
#my_var = ''
#my_var = #my_var.presence || 'This is a non-empty string'
Thanks :-)
in this case, i would just check the length of this string:
#my_var = ''
#my_var = 'This is a non-empty string' if #my_var.length == 0
=> "This is a non-empty string"
Related
I am working in rails. I have one doubt.
1. a = "ABCD123"
I want to print ABCD123
2. b = "ABCDE<123>"
I want to print ABCDE
For that I am using this
a.scan(/\b[A-Za-z]+\b/).join and
b.scan(/\b[A-Za-z]+\b/).join.
First one is giving nil but I want to print it as ABCD123 and second one is showing correct what I want.
Could anyone please help me. Thanks.
code below can remove all tags in the string
a = "ABCD123"
b = "ABCDE<123>"
a.gsub /<.*?>/, '' # => "ABCD123"
b.gsub /<.*?>/, '' # => "ABCDE"
def conversion(str)
index_number = str.index(/[\W_]+/)
if index_number.present?
main_str = str.gsub(str[index_number..],'')
else
main_str = str
end
return main_str
end
or you can use
b = "ABCD-123"
b.match(/(^[A-Za-z0-9]+)/)[1]
#=> "ABCD"
You can try following,
b = "ABCDE<123>"
b[/[^<>]+/]
# => "ABCDE"
Since comments are a bit limited:
Here is a small snippet to test different inputs.
strings = %w[ABCD123 ABCD<123> ABCD <123>ABCDE]
strings.each do |string|
match = string.match(/(^[A-Za-z0-9]+)/)
if match
puts "'#{string}' => #{match[1]}"
else
puts "'#{string}' does not match pattern"
end
end
Is this the desired behaviour?
'ABCD123' => ABCD123
'ABCD<123>' => ABCD
'ABCD' => ABCD
'<123>ABCDE' does not match pattern
In Rails console
> h_json = {key: "value"}.to_json;
#=> "{\"key\":\"value\"}"
> s_json = %Q|{"key": "value"}|
#=> "{\"key\": \"value\"}"
> s_json.class
#=> String
> h_json.class
#=> String
We can see both h_json and s_json have the same String class, and looks the same, however
#=> "{\"key\": \"value\"}"
> s_json == h_json
#=> false
They don't equals each other, I don't understand why.
there is a space in the s_json, if you checked the source code of the to_json function
# File activesupport/lib/active_support/json/encoders/hash.rb, line 33
def to_json(options = nil) #:nodoc:
hash = as_json(options)
result = '{'
result << hash.map do |key, value|
"#{ActiveSupport::JSON.encode(key.to_s)}:#{ActiveSupport::JSON.encode(value, options)}"
end * ','
result << '}'
end
this function doesn't add a space between the colon : and the value.
So actually,
h_json = "{\"key\":\"value\"}"
and
s_json = "{\"key\": \"value\"}"
if you set s_json = "{\"key\":\"value\"}" they must be equal.
In the code below I'm trying to append text to a string value if a key is defined. If the key is not defined then it simply defines the key/value pair with the text.
if my_hash.key?(:my_key)
my_hash[:my_key] << 'My text'
else
my_hash[:my_key] = 'My text'
end
Is there a better way to do this?
You can define a hash that defaults to an empty string. Then, you do not have to take care of null values:
hash = Hash.new { |h, k| h[k] = '' }
hash[:key] << 'string'
puts hash
# => { :key => 'string' }
As suggested by MrYoshiji and Damien Roche the solution to the question is the following:
my_hash[:my_key] = my_hash[:my_key].to_s + 'My text'
Furthermore, if the text should be separated by a space in case :my_key was defined value this can be done:
my_hash[:my_key] = [ my_hash[:my_key].to_s, 'My text' ].reject(&:empty?).join(' ')
This could then be wrapped up in a helper function to make things a little easier:
def add_str(str, new_str)
[str.to_s, new_str].reject(&:empty?).join(' ')
end
my_has[:my_key] = add_str my_has[:my_key], 'My text'
I try to write to an string something like this:
arr << "Icd3code.create!({:text => '#{variable1}'})" + "\n"
My problem is that variable 1 is an string, that contains an ' :
variable1 = "Ami's house"
So that at the end the ouput of my code is this:
Icd3code.create!({:text => 'Ami's house'})
How you can see now i have one ' to much! I dont know what i can do to avoid this problem! Thanks
If I've understood, you want to loop over some input, building up a list of parameters, which you plan to later use to create some records. If that's the case, I think you're better off using hashes, instead of strings:
# Let's pretend this came from the big, bad, world
inputs = ["Ami's house", "Fred's house", "Jim's house"]
creation_params = []
inputs.each do |input|
creation_params << {:text => input}
end
Then you could create all the Icd3codes, like this:
creation_params.each do |params|
Icd3code.create!(params)
end
Or you could save them in a text file, for later:
File.open('dest', 'w') do |f|
f.write(creation_params.to_json)
end
variable1 = "Ami's house"
puts %Q[Icd3code.create!({:text => "#{variable1}"})] + "\n"
--output:--
Icd3code.create!({:text => "Ami's house"})
Im trying to read a column of String values from my DB. Im trying to convert them to floats. I have written the following method to do that
def initialize (db_listings)
db_listings.each do |listing|
name = listing.name
index = listing.id
lat_string = listing.latitude
long_string = listing.longitude
puts "name = #{name}"
puts "index = #{index}"
puts "Converting #{lat_string} to float"
puts "Converting #{long_string} to float"
if(lat_string == nil || long_string == nil )
lat_float = Float(9999)
long_float = Float(9999)
else
lat_float = Float(lat_string)
long_float = Float(long_string)
end
puts "Now printing floats"
puts lat_float
puts long_float
end
end
But I get the following error:
Throwing an error:ArgumentError: invalid value for Float(): ""
This is because it encountered an empty entry for that column.
My question is : WHy did the if else statement in my method not catch it?
How do I adjust my method for empty/invalid values in the database?
Thanks
From the error message I presume lat_string and long_string are empty strings rather than nil. You could use blank? to catch both nil and empty strings:
if(lat_string.blank? || long_string.blank?)
lat_float = Float(9999)
long_float = Float(9999)
else
lat_float = Float(lat_string)
long_float = Float(long_string)
end