how to apply gsub on string elements within an array? - ruby-on-rails

for example, I have an array which is structured as follow:
my_array = [["..\\..\\..\\Source\\file1.c"], ["..\\..\\..\\Source\\file2.c"]]
This array is produced by this code:
File.open(file_name) do |f|
f.each_line {|line|
if line =~ /<ClCompile Include="..\\/
my_array << line.scan(/".*.c"/)
end
}
end
Later in the code I'm working on the array:
my_array .each {|n| f.puts n.gsub(/\\/,"//")}
As you can see, would like to replace all the backslashes with forward slashes on the elements within the array. The elements presents paths to source files. On the end I will output these paths within an other file.
I get this error:
undefined method `gsub' for [["..\\..\\..\\Source\\file1.c"], ["..\\..\\..\\Source\\file2.c"]]:Array (NoMethodError)
Any idea?

You have an array of arrays, so if you want to keep it like that, you would need to have 2 loops.
Otherwise, if you change your variable to this: my_array = ["..\\..\\..\\Source\\file1.c", "..\\..\\..\\Source\\file2.c"] your code should work.
UPDATE
if you can not control my_array, and it is always an array of one item arrays, perhaps this is cleanest:
my_array.flatten.each {|n| puts n.gsub(/\\/,"//")}
What it does is transforms two-dimensional array in one-dimensional.

my_array.flatten.each { |n| f.puts n.tr('\\', '/') }

As others have pointed out, you are calling gsub on an array, not the string within it. You want:
my_array.each {|n| puts n[0].gsub(/\\/,"//")}

Related

Ruby to_s isn't converting integer to string

I'm trying to convert some values in a hash into a string but the type stays the same.
recommended_stores = []
results['data'].each do |stores_list|
stores_list['stores'].each do |store|
store['id'].to_s
end
recommended_stores << stores_list['stores']
end
Am I missing something here?
the method #to_s just returns the element converted to a string, but does not actually convert the element to a string permanently. instead of using #each, you could use #map, like this.
results['data'].map do |stores_list|
stores_list['stores'].each do |store|
store['id'] = store['id'].to_s
end
end
That would return an array of arrays, if you want it to be just one array you can use #flat_map.
you got everything but you are not storing it, i think assigning the value of hash with the value.to_s would work, can you try as below
recommended_store = []
results['data'].each do |stores_list|
stores_list['stores'].each do |store|
store['id'] = store['id'].to_s
end
recommended_store << stores_list['stores']
end
Note : in your question array declared is "recommended_store" and last line you are pushing elements in to "recommended_stores" hope its just a typo, and not the cause of problem :-)

Comparing two arrays and not getting expected output in rails console

I have the following controller action that builds two arrays.
current_event = Event.find(params[:event_id])
campaign_titles = Relationship::CampaignTitleRelationship.where(campaign_id: current_event.campaign_id)
campaign_title_ids = Array.new
campaign_titles.each do |title|
campaign_title_ids << [title.title_id]
end
event_title_ids = Array.new
params[:title_ids].each do |title|
event_title_ids << [title]
end
The two arrays output like this
[["6556"], ["9359"], ["11319"], ["12952"], ["14389"], ["14955"], ["16823"]]
[[6556], [9359], [11319], [12952], [14389], [14955], [16823]]
I'm trying to compare these two arrays using the - symbol, but am only getting an output of each id, instead of what I expect (nothing) since both arrays contain the same items.
I can see that the first array has quotations around each key inside the bracket. The second does not. How do I compare these two arrays?
Just add params as integers to your array
params[:title_ids].each do |title|
event_title_ids << [title.to_i]
end

How can I iterate over part of a hash in Ruby

In a Rails environment i get a params hash from a form.
Besides others, like
params[:vocab][:name]
params[:vocab][:priority]
I have the 3 fields tag_1, tag_2, tag_3 whose values are stored in
params[:vocab][:tag_1]
params[:vocab][:tag_2]
params[:vocab][:tag_3]
My question is:
Can I iterate over these three hash keys?
I want to do sth like
for i in 1..3 do
iterator = ":tag_" + i.to_s
puts params[:vocab][iterator.to_sym]
end
but that doesn't work.
Your approach doesn't work because:
':tag_2'.to_sym
# => :":tag_2"
so it would work if you remove leading colon from ":tag_" + i.to_s
You can also do it this way, iterating over keys:
[:tag_1, :tag_2, :tag_3].each { |key| puts params[:vocab][key] }
You can construct symbols via interpolation; prefixing a string with a colon will cause Ruby to interpret it as a symbol.
(1..3).each do |i|
puts params[:vocab][:"tag_#{i}"]
end

Getting data out of MatchData got as a result from match function

I have an array of custom objects in it. Those objects have a parameter called name which is a concatenation of 2 strings having a delimiter in between. Eg: name could be Some#Data where 'Some' is first string and 'Data' is another and # is a delimiter.
My intention is update the name parameter for all the objects inside the array such that the param would only have 'Data' (i.e. remove 'Some#') and store the objects inside another array after updating. Below is the code:
final_array = array1.select do |object|
object.name = object.name.match(/#(.*?)$/)
end
When I print object.name.match(/#(.*?)$/) this gives me output as:
#<MatchData "#Data" 1:"Data">
Out of this output, how do I get "Data" from this MatchData. I tried object.name.match(/#(.*?)$/)[1] but it didn't work. Or do I need to change my regex?
I would use #each and #gsub methods:
array.each do |object|
object.name = object.name.gsub(/^.+#/, '')
end

How can I iterate over array elements matching a regular expression?

Is there a method that can be used with "each" to filter array elements depending on a regular expression matching?
I have for example the following array:
arr = ["one", "has_two", "has_tree", "four"]
I want to loop into this array and to take only elements beginning with "has".
the following code is doing the loop for all the elements
arr.each |element| do
....
end
You can use Enumerable's grep method to do this:
arr.grep(/^has/).each do |element|
...
end
You can select the elements you're interested in, and then loop over those:
arr.select { |e| e[/^has/] }.each do |element|
end
I'd say:
arr.find_all{|el| el =~ /^has/}.each do...

Resources