Ruby variable regular expression in Array Select - arrays

I'm trying to exclude elements from an array of strings using array.select. I have this method:
def filter_out_other_bad_vals(array_of_strs, things_i_want)
array_of_strs = array_of_strs.select { |line| /"#{things_i_want}"/.match(line) }
end
I want to pass a string as a variable things_i_want. But this does not return any matches:
array = ["want_this", "do_not_want", "do_not_want","want_this", "want_this"]
pattern = 'want_this'
array = filter_out_other_bad_vals(array, pattern)
This returns an empty array. But if I hardcode the value in the match expression, I get what I want.
def filter_out_other_bad_vals(array_of_strs, things_i_want)
array_of_strs = array_of_strs.select { |line| /want_this/.match(line) }
end
How do I put a variable in the regex? What am I doing wrong?
I could just traverse the array, check each item, and then save the value in another array, but that's not very ruby-like, is it?

You include quotes in regex definition:
/"#{things_i_want}"/
remove them and it should work:
/#{things_i_want}/
EDIT:
By the way, you don't have to use regex for exact matching, you can use equality check (==) or #include? depending if you need a string to be equal to thing you want or just include it:
> array = ["want_this", "do_not_want", "do_not_want","want_this", "want_this"]
> array.select{|line| line == 'want_this'}
# => ["want_this", "want_this", "want_this"]
> array.select{|line| line.include? 'want_this'}
# => ["want_this", "want_this", "want_this"]

Related

How to check for Hash value in an array?

Heres my set up
project_JSON = JSON.parse
teamList = Array.new
project = Hash.new()
project["Assignee Name"] = issue["fields"]["assignee"]["displayName"]
project["Amount of Issues"] = 0
if !teamList.include?(issue["fields"]["assignee"]["displayName"])
project_JSON.each do |x|
project["Amount of Issues"] += 1
teamList.push(project)
end
Im having trouble with this line.
if !teamList.include?(issue["fields"]["assignee"]["displayName"])
It always returns true even after the .push. I want to make an array of my team members and list how many times their name appears in my JSON. What am I doing wrong and how do I dynamically refer to a hash value in an if statement(thats where I think its wrong because if I am saying .include?(issue["fields"]["assignee"]["displayName"]) wrong then its nil and the if statement will always be true)?
In your code teamList is an empty array, so it does not include? anything, it will always return false. Now because you are using ! operator it always returns true.
EDIT
If understood it right, you have to loop through the array checking each element for the value specified.
Below is a way to do it, mind you I replaced keys for symbols as it's a good practice in Ruby:
issue = {
:fields => {
:assignee => {
:displayName => 'tiago'
}
}
}
teamList = Array.new
def teamList.has_assignee?(assignee)
self.each do |e|
return e[:assignee] == assignee
end
false
end
project = Hash.new
project[:assigneeName] = issue[:fields][:assignee][:displayName]
project[:amountOfIssues] = 0
teamList.push(project) unless teamList.has_assignee? issue[:fields][:assignee][:dsiplayName]
teamList.push(project) unless teamList.has_assignee? issue[:fields][:assignee][:dsiplayName]
puts teamList.inspect # only one object here
As Sergio pointed out you could use .detect
def teamList.has_assignee?(assignee)
self.detect { |e| e[:assigneeName] == assignee }
end

Removing object from Array

How can you remove a specific object from an Array of string.
array = ["mac","iPhone","iPad"]
Is there a method to delete a specific string in the array, like for example i wanted to remove "iPhone", without using removeAtIndex(1)
Use filter for that purpose
var array = ["mac","iPhone","iPad"]
array = array.filter() { $0 != "mac" }
print(array) // will print ["iPhone", "iPad"]

First array element that matches an element in another array

I'm trying to return the first element in the given array that matches an element in a preset array. I have this:
def find_the_cheese(a)
cheese_types = ["cheddar", "gouda", "camembert"]
a.collect{|c| cheese_types.include?(c)}.include?(true)
end
But it returns true rather than the c value from the enclosed brackets. How can I return the matching element?
Following code will returning elements from food which include in cheese_types
def find_the_cheese(food)
cheese_types = ["cheddar", "gouda", "camembert"]
food & cheese_types
end
The Array class includes the Enumerable module. Enumerable#find does just that:
def find_the_cheese(foods)
cheeses = ["cheddar", "gouda", "camembert"]
foods.find { |food| cheeses.include?(food) }
end
CheeseTypes = ["cheddar", "gouda", "camembert"]
def find_the_cheese(a)
(a & CheeseTypes).first
end

Merging two arrays of Capybara elements

This is similar to something I posted yesterday but i got mixed up with what I actually had in front of me. I have two arrays that need merging into the same index value but I have capybara elements as opposed to strings and integers.
Example
#returned_names = page.all('#results > table.result > tbody > tr.data:first-of-type > td')
#returned_yobs = page.all('#results > table.result > tbody > tr.data:nth-child(2) > td')
# Returns
#returned_names = [#<Capybara::Element tag="td">, #<Capybara::Element tag="td">, #<Capybara::Element tag="td">]
#returned_yobs = [#<Capybara::Element tag="td">, #<Capybara::Element tag="td">, #<Capybara::Element tag="td">]
So based on yesterday's answer to merge these together, matching index values I should do
#collection = #returned_names.zip(#returned_yobs).map { |r| r.join(' ') }
# Returns
["#<Capybara::Node::Element:0x000000038c50e8> #<Capybara::Node::Element:0x000000036fadf8>",
"#<Capybara::Node::Element:0x000000038c50c0> #<Capybara::Node::Element:0x000000036fadd0>",
"#<Capybara::Node::Element:0x000000038c5020> #<Capybara::Node::Element:0x000000036fada8>"]
Which so far looks like it's doing the right thing. I need to then convert this to an array of its text values, but when I do
#collection.map { |t| t.text }
I get an error
undefined method `text' for #<String:0x00000001938310>
I'm guessing I can't map from here as I don't have an enumerable object at this stage?
Is there a way to get #collection back to an enumerable object so that I can then map the text values ?
Array#join converts each object (i.e. node) to a string. This should work:
#returned_names.zip(#returned_yobs).map { |name, yob| "#{name.text} #{yob.text}" }
how about this:
#collection.each { |capybara_element| }.map(&:text)
or more verbose but would do the same thing:
#text_collection = []
#collection.each do |element|
#text_collection.push(element.text)
end

Scala Converting Each Array Element to String and Splitting

I have an array loaded in, and been playing around in the REPL but can't seem to get this to work.
My array looks like this:
record_id|string|FALSE|1|
offer_id|decimal|FALSE|1|1,1
decision_id|decimal|FALSE|1|1,1
offer_type_cd|integer|FALSE|1|1,1
promo_id|decimal|FALSE|1|1,1
pymt_method_type_cd|decimal|FALSE|1|1,1
cs_result_id|decimal|FALSE|1|1,1
cs_result_usage_type_cd|decimal|FALSE|1|1,1
rate_index_type_cd|decimal|FALSE|1|1,1
sub_product_id|decimal|FALSE|1|1,1
campaign_id|decimal|FALSE|1|1,1
When I run my command:
for(i <- 0 until schema.length){
val convert = schema(i).toString;
convert.split('|').drop(2);
println(convert);
}
It won't drop anything. It also is not splitting it on the |
Strings are immutable, and so split and drop don't mutate the string - they return a new one.
You need to capture the result in a new val
val split = convert.split('|').drop(2);
println(split.mkString(" "));
Consider also defining a lambda function for mapping each item in the array, where intermediate results are passed on with the function,
val res = schema.map(s => s.toString.split('|').drop(2))

Resources