In a ruby-script I have two arrays
exclude = ['bgb400', 'pip900', 'rtr222']
result = ['pda600', 'xda700', 'wdw300', 'bgb400', 'ztz800', 'lkl100']
I want to iterate over the result array and remove any string that exists in the exclude array. In the end the string 'bgb400' should be removed from the result array.
Use operator -
irb(main):004:0> result - exclude
=> ["pda600", "xda700", "wdw300", "ztz800", "lkl100"]
If you really need to modify your result array you can use reject!. However if it is the case, you better review your code.
result.reject! {|s| exclude.include? s}
simply do:
new_result = result - exclude
=> ["pda600", "xda700", "wdw300", "ztz800", "lkl100"]
actually what it does is check for matching entries in both arrays and produce the result excluding the matching entries.
It sounds like Array#delete_if method is best for this task.
exclude = ['bgb400', 'pip900', 'rtr222']
result = ['pda600', 'xda700', 'wdw300', 'bgb400', 'ztz800', 'lkl100']
In order to remove elements in the reuslt array that are included in the excude array try this
result.delete_if{|r|exclude.include?('r')}
Related
Persoane = []
Nume = gets
Persoane.push Nume.split(",")
puts Persoane.sort
I am trying to get an user to input carachters that get split into substrings which get inserted in an array, then the program would output the strings in alphabetical order. It doesnt seem to work and I just get the array's contents, like so:
PS C:\Users\Lenovo\Desktop\Ruby> ruby "c:\Users\Lenovo\Desktop\Ruby\ruby-test.rb"
Scrie numele la persoane
Andrei,Codrin,Bradea
Andrei
Codrin
Bradea
PS C:\Users\Lenovo\Desktop\Ruby>
you can do this :
Nume = gets
puts Nume.split(",").sort
or in 1 line
array = gets.chomp.split(",").sort
The error is because of your use of push. Let's assume that you define the constant Nume by
Nume='Andrei,Codrin,Bradea'
Then, Nume.split(',') would return the Array ['Andrei', 'Codrin', 'Bradea']. When you do a Persoane.push, the whole array is added to your array Persoane as a single element. Therefore, Persoane contains only one Element, as you can verify when you do a
p Persoane
If you sort a one-element array, the result will also be just that one element - there is nothing to sort.
What you can do is using concat instead of push. This would result in Persoane being a 3-element array which can be sorted.
I'm not sure you need use constants here
If you don't need keep user input and use it somewhere, you can just chain methods like this
persons = gets.chomp.split(",").sort
For something a little different, let's not split at all.
people = gets.scan(/[^,]+/).map(&:strip).sort
This will avoid problems like multiple commas in a row yielding empty strings. Of course, you could also avoid that with:
people = gets.split(/\,+/).map(&:strip).sort
I have the following array:
arr = [["Example"]]
I need to reduce it to just "Example" (basically, just remove the array).
I know I could do arr[0][0], but am curious if there's a simple method to just remove the string from the array without using indexes.
For clarification...there will only ever be a single item in the array.
For a single item, you can use:
[['array']].join
=> 'array'
Updated with more examples
If you have multiple items, the strings will be combined:
[['array'], ['array']].join
=> 'arrayarray'
And if you pass a parameter to the join method:
[['array'], ['array']].join('&')
=> 'array&array'
While this is not as efficient as [0][0], it will still work:
arr.flatten.first
I have a method which returns the number of hotels from a webpage:
hotel_count = self.getHotelsList.values
The output of this method is:
[["hotel_0", "hotel_1", "hotel_2", "hotel_3", "hotel_4", "hotel_5", "hotel_6", "hotel_7", "hotel_8", "hotel_9", "hotel_10", "hotel_11", "hotel_12", "hotel_13", "hotel_14", "hotel_15", "hotel_16", "hotel_17", "hotel_18", "hotel_19", "hotel_20", "hotel_21", "hotel_22", "hotel_23", "hotel_24", "hotel_25", "hotel_26", "hotel_27", "hotel_28", "hotel_29", "hotel_30", "hotel_31", "hotel_32", "hotel_33", "hotel_34", "hotel_35", "hotel_36", "hotel_37", "hotel_38", "hotel_39", "hotel_40"]]
I want to know the length of this array, but if I write
hotel_count = self.getHotelsList.values.length
The length is 1. How can I get a length of 41, which is the one I'm expecting?
Thanks
The array you are showing is nested inside another array. So the outer array is of length 1, the inner array is what you want.
To get it you have to first get the first element of the outer array using [0] or first
testList[0].length
testList.first.length
I am not sure why your getHotelsList method returns a nested array, it doesn't appear to need it.
hotel_count = getHotelsList.values.first.length
You can also do it with [0], but first is faster.
Two notes:
You don't need self at the beginning.
It is a bad habit to use camel case for method names in Ruby. it should better be get_hotels_list.
You could convert that into a single array with flatten:
hotel_count = self.getHotelsList.values.flatten.size
I am collecting HTTP response and it comes back in the text/json form. The original format is as follows:
{"param" => "value", "interesting_param" => [{"parama1"=>vala1,"parama2"=>vala2,"parama3"=>vala3,"parama4"=>vala4,"parama5"=>vala5},
{"paramb1"=>valb1,"paramb2"=>valb2,"paramb3"=>valb3,"paramb4"=>valb4,"paramb5"=>valb5}]}
When I do a JSON.parse(response.body)["interesting_param"], I can retrieve this output:
{"parama1"=>vala1,"parama2"=>vala2,"parama3"=>vala3,"parama4"=>vala4,"parama5"=>vala5},
{"paramb1"=>valb1,"paramb2"=>valb2,"paramb3"=>valb3,"paramb4"=>valb4,"paramb5"=>valb5}
How can I capture only the following from the full result-set above.
`parama1-vala1`, `parama2-vala2` and `parama5-vala5`
`paramb1-valb1`, `paramb2-valb2` and `paramb5-valb5`
Update
I did try further on this & now I am thinking of making use of loop.
The way I am attempting to do this is:
Find the count of records, for example, if:
test =
{"parama1"=>vala1,"parama2"=>vala2,"parama3"=>vala3,"parama4"=>vala4,"parama5"=>vala5},
{"paramb1"=>valb1,"paramb2"=>valb2,"paramb3"=>valb3,"paramb4"=>valb4,"paramb5"=>valb5}
Then, test.count will be 2.
Now if somehow I can use a loop to iterate over elements in test, then I might be able to capture specific elements.
Thanks.
It looks like you want to map each hash into a list of strings made by joining the string version of the key with the string version of the value, joined by a '-'.
JSON.parse(response.body)["interesting_param"]
The above code should give you a ruby list of hashes.
interesting_bits = JSON.parse(response.body)["interesting_param"]
result = interesting_bits.map{|bit| bit.map{|k,v| "#{k}-#{v}"}}
Something like that should do the trick.
puts result.inspect
#prints
# [ ["parama1-vala1","parama2-vala2","parama3-vala3","parama4-vala4","parama5-vala5"] , ["paramb1-valb1","paramb2-valb2","paramb3-valb3","paramb4-valb4","paramb5-valb5"] ]
I don't understand what criteria you are using for then filtering this down to just 1,2 and 5... but that is easily done too. I would do that to the hashes before converting them to string lists.
I know split is a useful tool and I know there is a way to do this. I tried a few different methods but couldn't figure it out via google. Can anyone help me.
example1 = "test1,test2,test3,test4,test5"
example2 = "test1,test2,test3,test4,test5,test6,test7"
So I need the result to look like this
example1 = test3,test4,test5
example2 = test5,test6,test7
I would like to keep the comma's too.
example = "test1,test2,test3,test4,test5"
example.split(',')[-3..-1] # => [test3,test4,test5]
Split gives you an array. You can use ranges to select subsets of an array. The negative numbers are counting from the end of the array, so [-3..-1] selects the third last to the last element.
This is basically just split and join on commas. Negative indexes into an array will easily get you the last however-many elements. So I think you want str.split(',')[-3..-1].join(',').
You can also use last(3) instead of [-3..-1], like this:
example = "test1,test2,test3,test4,test5"
example.split(',').last(3).join(',') # => "test3,test4,test5"