How to remove an array from another array in Ruby? - ruby-on-rails

I have a nested array in Ruby:
array = [["a", "b"], ["c", "d"]]
What command can I use to remove the nested array that contains "a" from the array?
Thanks for any help.

array.delete_if{|ary| ary.kind_of?(Array) and ary.include?('a') }
Deletes all arrays which include "a"

Do you specifically want to remove ["a", "b"], knowing that's exactly what it is, or do you want to remove any and all arrays that contain "a", no matter their remaining values? It's not clear whether you meant 'the nested array that contains "a"' as part of the problem specification, or just a way of indicating which of the elements in your specific example you wanted the answer to target.
For the first one, you can use DigitalRoss's answer.
For the second, you can use Huluk's, but it's overly specific in another way; I would avoid the kind_of? Array test. If you know the elements are all arrays, then just assume it and move on, relying on exceptions to catch any, well, exceptions:
array.delete_if { |sub| sub.include? 'a' }
If you do need to test, I would use duck-typing instead of an explicit class check:
array.delete_if { |item| item.respond_to? :include? and item.include? 'a' }

> [["a", "b"], ["c", "d"]] - [["a", "b"]]
=> [["c", "d"]]
If you don't already have a handle on the element other than knowing it contains an "a", you can do:
array - [array.find { |x| x.include? "a" }]

Try this:
array.delete_if { |x| x.include? "a" }

Related

2 arrays insert via (column) double dimension array ruby (short method) [duplicate]

I am browsing through the ruby Array iterators. And I can't find what I am looking for and I think it already exists:
I have two arrays:
["a", "b", "c"]
[0,1,2]
And I want to merge as so:
[ [0, "a"], [1, "b"], [2, "c"] ]
I think the iterator exists in the standard library (I used it before) but I am having trouble finding its name.
This should work:
[0,1,2].zip(["a", "b", "c"]) # => [[0, "a"], [1, "b"], [2, "c"]]
From the official documentation of the Array#zip function:
Converts any arguments to arrays, then merges elements of self with corresponding elements from each argument.
This generates a sequence of ary.size n-element arrays, where n is one more than the count of arguments.
For more info and some other examples, refer to:
https://ruby-doc.org/core-2.4.2/Array.html#method-i-zip
You are looking for the zip function
https://apidock.com/ruby/Array/zip
I think you could use https://apidock.com/ruby/Enumerator/each_with_index
See this post difference between each.with_index and each_with_index in Ruby?
or if you have specific values and you want to map them you would use map or zip. It explains it well in this post
Combine two Arrays into Hash

Iterating an Array by an Array (Another Ruby Word Count)

Having some trouble figuring out the logic for a ruby word count. My goal is to pass in some text, and get the total count of a certain category of words as defined in an array. So if I gave the following variables, I'd want to find out the fraction of words mentioned that have anything to do with fruit:
content = "I went to the store today, and I bought apples, eggs, bananas,
yogurt, bacon, spices, milk, oranges, and a pineapple. I also had a fruit
smoothie and picked up some replacement Apple earbuds."
fruit = ["apple", "banana", "fruit", "kiwi", "orange", "pear", "pineapple", "watermelon"]
(I realize plural/singular is not consistent; just an example). Here's the code I've been trying:
content.strip
contentarray = content.downcase.split(/[^a-zA-Z]/)
contentarray.delete("")
total_wordcount = contentarray.size
IRB Test:
contentarray.grep("and")
=> ["and", "and", "and"]
contentarray.grep("and").count
=> 3
So then I try:
fruit.each do |i|
contentarray.grep(i).count
end
=> ["apple", "banana", "fruit", "kiwi", "orange", "pear", "pineapple", "watermelon"]
It just returns the array, no counts. I would add them all up after if it returned any numbers. The goal is to end up with:
fruitwordcount
=> 6 / 33
or
=> .1818181
I've tried searching and found a lot of methods saying to convert the content array to a hash count occurrences as many tutorials do, but that gives the count of every single word when I need the counts of only a subset. I can't seem to find a good way to search an array or string of words by an array of strings. I found a few articles saying to use a histogram from the Multiset gem, but that's still giving every word. Any help would be very much appreciated; please forgive my n00bery.
Fruit#each just iterates the fruits, while you likely want to collect value. map comes to the rescue:
result = fruit.map do |i|
[i, contentarray.grep(i).count]
end
Whether you need a hash of fruit ⇒ count, it’s simple:
result = Hash[result]
Hope it helps.
The method you are looking for is map, not each: each executes the block for each element in the array, and then returns the original array. map creates a new array containing the values returned by the block.
fruit.map do |i|
contentarray.grep(i).count
end
=> [1, 0, 1, 0, 0, 0, 1, 0]
It's because the each method just iterates and executes the block. Use map or collect to execute the block and return an array.
result = fruit.map { |i| counterarray.grep(i).count }
array#each returns the array itself as per ruby docs.
You probably want to try to give some of the other methods a try. Especially count and map look promising:
fruit.map do |f|
contentarray.count{|content| content == f}
end
To get just the fruits get your array - contentarray.keep_if{|x| fruit.include?(x) } then turn it into a hash count in the way you've found tutorials do.
Or just use inject on the contentarray to build the hash
contentarray.inject(Hash.new(0)) do |result, element|
if fruit.include?(element)
result[element] += 1
end
result
end
Hash.new(0) sets the default value to 0 so we can just add one

Removing a "subset" from an array in Ruby

I want to remove some elements from an array contained in another array.
The way to do this in Java is:
myArray.removeAll(anotherArray)
This code removes the elements contained in anotherArray from myArray.
Is there something like removing the elements contained in myArray INTERSECTION anotherArray from myArray?
Yes, this is what the - operator (really Array#- method) is for:
a = [1, 2]
b = [2]
a - b
# => [1]
Use "Array Difference"
There's more than one way to do this in Ruby, but the most common is to call the array difference method Array#-. The documentation for this method says:
Returns a new array that is a copy of the original array, removing any items that also appear in other_ary. The order is preserved from the original array.
It compares elements using their hash and eql? methods for efficiency.
[ 1, 1, 2, 2, 3, 3, 4, 5 ] - [ 1, 2, 4 ] #=> [ 3, 3, 5 ]
If you need set-like behavior, see the library class Set.
The minus sign looks like an operator, but is actually a method call on the first Array object. Obviously, you could also look at Set#difference if you're working with Set objects rather than an Array.

How to update item inside an embedded array without adding a new item in Parse

For example, I have arrays embedded inside array [["A", 4], ["B", 5]], and I would like to update the element inside the first embedded array so that the final outcome because [["A", 5], ["B", 5]], and not [["A", 4], ["B", 5], ["A", 5]].
Before replace value of your array make sure you have NSMutableArray (mutable) ?
Otherwise you get error:
Yes i have NSMutableArray then follow my suggestion: (Here i give simple basic logic)
For replace any value at specific Index of NSMutableArray, UsereplaceObjectAtIndex:withObject:.
For Example
[MyArrayName replaceObjectAtIndex:0 withObject:MyValues];
Apply this logic:

How to create object array in rails?

I need to know how to create object array in rails and how to add elements in to that.
I'm new to ruby on rails and this could be some sort of silly question but I can't find exact answer for that. So can please give some expert ideas about this
All you need is an array:
objArray = []
# or, if you want to be verbose
objArray = Array.new
To push, push or use <<:
objArray.push 17
>>> [17]
objArray << 4
>>> [17, 4]
You can use any object you like, it doesn't have to be of a particular type.
Since everything is an object in Ruby (including numbers and strings) any array you create is an object array that has no limits on the types of objects it can hold. There are no arrays of integers, or arrays of widgets in Ruby. Arrays are just arrays.
my_array = [24, :a_symbol, 'a string', Object.new, [1,2,3]]
As you can see, an array can contain anything, even another array.
Depending on the situation, I like this construct to initialize an array.
# Create a new array of 10 new objects
Array.new(10) { Object.new }
#=> [#<Object:0x007fd2709e9310>, #<Object:0x007fd2709e92e8>, #<Object:0x007fd2709e92c0>, #<Object:0x007fd2709e9298>, #<Object:0x007fd2709e9270>, #<Object:0x007fd2709e9248>, #<Object:0x007fd2709e9220>, #<Object:0x007fd2709e91f8>, #<Object:0x007fd2709e91d0>, #<Object:0x007fd2709e91a8>]
Also if you need to create array of words next construction could be used to avoid usage of quotes:
array = %w[first second third]
or
array = %w(first second third)

Resources