I'm counting string length as shown below:
if(key['name'].to_s.chars.length==0)
key['name']="Others"
end
And on ruby 2.1.8p440 it works, but on ruby 1.9.3p551 it throws following error:
(undefined method `length' for #<Enumerator: "Latency":chars>):
I cannot update 1.9.3 I must change this code.
What’s wrong with more explicit:
key['name'] = "Others" if key['name'].to_s.empty?
that works everywhere?
BTW, in ruby 1.9.3 there is no Enumerable#length there is Enumerable#count. The alias length it received later.
In Ruby 1.9.3 String#chars
Passes each character in str to the given block, or returns an enumerator if no block is given.
So converting it to an array before calling length should solve the issue:
key['name'].to_s.chars.to_a.count == 0 # or size ?
try key['name'].to_s.mb_chars.length . hope this will help u .
You question is tagged with ruby-on-rails which has the blank? and presence methods. With that methods I would write something like:
if key['name'].blank?
key['name'] = 'Others'
end
Or:
key['name'] = 'Others' if key['name'].blank?
Or:
key['name'] = key['name'].presence || 'Others'
Related
So I have the following code:
new = #params[collection.to_s + '_attributes']
old = #model.send collection
if new.nil?
old.clear
else
new_records = new.map { |_, e| e[:id] }
if !new_records.nil? && !old.nil?
old.not_in(id: new_records).destroy_all
end
end
The problem is I didn't use 'push' function anywhere in my code and based on the stacktrace the error occurs when executing:
old.not_in(id: new_records).destroy_all
I'm new to Rails so I hope someone can help me. Thanks in advance!
UPDATE
I ended up using delete_all instead of destroy_all for now. I think it was causing the error. It's working now but it would really be nice if I could find out why it wasn't working with destroy_all.
I don't think not_in is rails command, Instead, try
old.where.not(id: new_records).destroy_all
or, not in can be used like this.
old.where('id NOT IN (?)',new_records).destroy_all
Try:
old.where.not(id: [new_records]).destroy_all
Not in always requires array.
I have a string that has the following value:
ucp-1.1.0_dtr-2.0.0
I am trying to fetch only 1.1.0 from the string. I am using the following code but it doesn't seem to work
substring = ucp-1.1.0_dtr-2.0.0.gsub('ucp-','')
String's [] and a simple regex will do it:
'ucp-1.1.0_dtr-2.0.0'[/[\d.]+/] # => "1.1.0"
This works because the search will stop as soon as it matches, so the first occurrence wins resulting in 1.1.0.
If you wanted the second/last occurrence then adding $ tells the regex engine to only look at the end of the line for the matching pattern:
'ucp-1.1.0_dtr-2.0.0'[/[\d.]+$/] # => "2.0.0"
The Regexp documentation covers all this.
substring = "ucp-1.1.0_dtr-2.0.0".gsub('ucp-','').split("_").first untried.
using regex with ruby string methods you can achieve this..
"ucp-1.1.0_dtr-2.0.0"
version = "ucp-1.1.0_dtr-2.0.0".scan(/[0-9_]/).join(".").split("_").first.slice(0..-2)
Or with your code you can try this..
substring = "ucp-1.1.0_dtr-2.0.0".gsub('ucp-','').split("_").first
Try this (verified):
"ucp-1.1.0_dtr-2.0.0".match(/^.-(.)_.-.$/)[1]
I've got a problem in doing some metaprogramming in Ruby / Rails which must be minor, but I can't get the clue.
I wan't to assign values to an active record relation, with my model having attributes:
MyModelClass.p1_id,
.p2_id,
...
.p8_id
SecondModel.position #Integer in (1..8)
I now want to do the following
sms = SecondModel.where(:xyz => 'bla')
sms.each do |sm|
mmc = MyModellClass.first
mmc.#somehow construct method here = sm.id
end
So that somehow this is accomplished
mmc.p1_id = sm.id
mmc.p2_id = sm.id
..
mmc.p8_id = sm.id
To sum up: I want to create that p*n*_id stuff dynamically, but I can't find out, how to tell Ruby, that this should be a method. I tried so far:
mmc.send('p#{sm.position.to_s}_id'.to_sym) = sm.id
But this doesn't work. Any clues?
You were close. Try this:
mmc.send("p#{sm.position.to_s}_id=", sm.id)
Here we call the method with = and pass the value of attribute as the second argument of send
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'm on Rails 2.3 and I'm trying to convert a string that is JSON-formatted to a Rails hash. However, when I use JSON.parse I get a JSON string without the delimiters:
{"source_id":40007,"object":"86088947610496.1","coursewalk_id":"86088947610477.1","description":"","image_uri":"db\/db-files\/
Image_2011-09-24_14.37.37__0000.jpg","latitude":"38.0113439821061","letter":"","letter_A":"","letter_B":"","letter_C":"","lett
er_D":"","letter_E":"","letter_F":"","longitude":"-78.7576854509104","number":"1","mcw_id":71}
Results of JSON.parse:
number1letter_Bcoursewalk_id86088947610477.1letter_Clatitude38.0113439821061letter_Dletter_Eletter_Fmcw_id71longitude-78.75768
54509104letterdescriptionobject86088947610496.1source_id40007letter_Aimage_uridb/db-files/Image_2011-09-24_14.37.37__0000.jpg
Code:
puts string_to_parse
fence_parsed = JSON.parse(string_to_parse)
puts fence_parsed
Any ideas?
Thanks,
Nick
That's just because you're using "puts". If you just type fence_parsed, or p fence_parsed you'll get what you're looking for. puts calls to_s. I hope this clears it up for you, if not let me know and I'll elaborate.