logo
down
shadow

ruby .each to compare with index before


ruby .each to compare with index before

By : Rodrigo Vimieiro
Date : November 22 2020, 02:59 PM
wish helps you I'm having trouble understanding the benefits of using of methods vs normal looping in Ruby at times. Methods seem much less flexible to me. For ex. the .each vs a while loop. ,
How would I do this with a .each?
code :
array.each_with_index do |value, i|
    if value > array[i+1]
        return true
    end
end
irb(main):023:0> array = [5,4,3,2,1]
# => [5, 4, 3, 2, 1]
irb(main):024:0> array.each_cons(2) { |pair| puts "true" if pair[0] > pair[1] }
true
true
true
true
# => nil


Share : facebook icon twitter icon
Ruby: Idiomatic way to compare every index of array to all other indexes of the same array?

Ruby: Idiomatic way to compare every index of array to all other indexes of the same array?


By : Eun Jee Shin
Date : March 29 2020, 07:55 AM
This might help you The following method requires only a single pass through the array. It returns all pairs of indices of elements of the array that sum to zero.
Code
code :
def zero_summing_pairs(arr)
  processed = {}
  arr.each_with_index.with_object([]) do |(n,i),pairs|
    processed[-n].each { |j| pairs << [j,i] } if processed.key?(-n)
    (processed[n] ||= []) << i
  end
end
zero_summing_pairs [7,0,4,-7]
  #=> [[0, 3]] 
zero_summing_pairs [7,4,0,7,4,0,-7,-4,-7]
  #=> [[2, 5], [0, 6], [3, 6], [1, 7], [4, 7], [0, 8], [3, 8]]
arr = [7,0,4,-7]
zero_summing_pairs(arr).map { |i,j| [arr[i], arr[j]] }
  #=> [[7, -7]] 

arr = [7,4,0,7,4,0,-7,-4,-7]
zero_summing_pairs(arr).map { |i,j| [arr[i], arr[j]] }
  #=> [[0, 0], [7, -7], [7, -7], [4, -4], [4, -4], [7, -7], [7, -7]]
(processed[n] ||= []) << i
processed[n] = (processed[n] || []) << i
processed[n] = processed[n] << i
processed[n] = (processed[n] || []) << i
             = (nil || []) << i      
             = [] << i
             = [i]
arr = [7,0,4,-7]

processed = {}
enum0 = arr.each_with_index
  #=> #<Enumerator: [7, 0, 4, -7]:each_with_index>
enum0.to_a
  #=> [[7, 0], [0, 1], [4, 2], [-7, 3]] 
enum1 = enum0.with_object([])
  #=> #<Enumerator: #<Enumerator: [7, 0, 4, -7]:each_with_index>:with_object([])> 
enum1.to_a
  #=> [[[7, 0], []], [[0, 1], []], [[4, 2], []], [[-7, 3], []]] 
(n,i), pairs = enum1.next
      #=> [[7, 0], []] 
n     #=> 7 
i     #=> 0
pairs #=> [] 
processed.key?(-n)
  #=> processed.key?(-7)
  #=> false
(processed[n] ||= []) << i
  #=> processed[n]
  #=> [i]
  #=> [0]
processed
  #=> {7=>[0], 0=>[1]}
pairs
  #=> [] 
(n,i), pairs = enum1.next
  #=> [[0, 1], []] 
processed.key?(-n)
  #=> processed.key?(0)
  #=> false 
(processed[n] ||= []) << i
  #=> (processed[0] ||= []) << 1
  #=> [] << 1
  #=> [1]
processed
  #=> {7=>[0], 0=>[1]}
pairs
  #=> [] 
(n,i), pairs = enum1.next
  #=> [[4, 2], []] 
processed.key?(-n)
  #=> processed.key?(-4)
  #=> false 
(processed[n] ||= []) << i
  #=> (processed[4] ||= []) << 2
  #=> [] << 2
  #=> [2] 
processed
  #=> {7=>[0], 0=>[1], 4=>[2]} 
pairs
  #=> [] 
(n,i), pairs = enum1.next
  #=> [[-7, 3], []] 
processed.key?(-n)
  # processed.key?(7)
  #=> true 
processed[-n].each { |j| pairs << [j,i] }
  # processed[7].each { |j| pairs << [j,3] }
  #=> [0] 
(processed[n] ||= []) << i
  #=> (processed[-7] ||= []) << 3
  #=> [] << 3
  #=> [3] 
processed
  #=> {7=>[0], 0=>[1], 4=>[2], -7=>[3]} 
pairs
  #=> [[0, 3]] 
(n,i), pairs = enum1.next
  #=> StopIteration: iteration reached an end (an exception)
Compare arrays with index ruby

Compare arrays with index ruby


By : hasuuser
Date : March 29 2020, 07:55 AM
it should still fix some issue Your question is not clear.
If you are interested in the values of array1 at the positions at which the values do not match, you might want to use this:
code :
array1 = [1,2,3,4]
array2 = [1,2,4,5]

array1.zip(array2).map { |a, b| a if a != b }
#=> [nil, nil, 3, 4]
array1.zip(array2).map.with_index { |(a, b), i| i if a != b }
#=> [nil, nil, 2, 3]
Compare two text files and print content of one with index of second with ruby

Compare two text files and print content of one with index of second with ruby


By : DarkTobi
Date : March 29 2020, 07:55 AM
Any of those help I think your main issues are that you are including the dash from the first file and that you are joining with an empty string instead of the regex | and not removing the empty strings. You are also only matching against the literal regex /reg/, not the variable reg.
For minimal changes to your code, you can get it work by using:
code :
f = open("file1.txt").readlines()

v=[]

for line in f
  v.push(line[1..-2]) # changed this line
end

reg = Regexp.union(v.reject(&:empty?)) # changed this line

printing = false

File.open("file2.txt").each_line do |line|
  printing = true if line =~ reg # changed this line

  puts line if printing

  printing = false if line =~ /Complete/
end
v = File.open("file1.txt").each_line.with_object([]) do |line, v|
  line = line[/-(\w+)/, 1]

  v << line if line
end

File.open("file2.txt").each_line do |line|
  if v.include?(line[/Read id: (\w+)/, 1])..(line.match?(/Complete/))
    puts line
  end
end
Pandas compare index value to corresponding index value to find a percentage match

Pandas compare index value to corresponding index value to find a percentage match


By : user3151953
Date : March 29 2020, 07:55 AM
I hope this helps you . You can use itertools to calculate the product of all unique Col A and then calculate the pct and build a new df:
code :
from itertools import product

# for each unique element in colA, build a list of unique elements from ColB
g = (
    df.groupby('ColumnA').ColumnB
    .apply(lambda x: x.values.tolist())
)

# generate a combination of all the lists 
prod = list(product(g, repeat=2))

data = (
    #for each pair of lists, find the number of common elements,
    #then divide by the union of 2 lists. This gives you the pct.
    np.array([len(set(e[0]).intersection(e[1]))/len(set(e[0]).union(e[1])) for e in prod])
    .reshape(len(g), -1)
)

pd.DataFrame(data*100, index=g.index.tolist(), columns=g.index.tolist())

        TestA   TestB   TestC   TestD
TestA   100.0   20.0    40.0    25.0
TestB   20.0    100.0   25.0    0.0
TestC   40.0    25.0    100.0   0.0
TestD   25.0    0.0     0.0     100.0
How to compare arrays based on the value contained on a certain index in Ruby?

How to compare arrays based on the value contained on a certain index in Ruby?


By : Shabawazawhodo
Date : March 29 2020, 07:55 AM
wish help you to fix your issue I have two arrays, one with strings that are questions and the other one with it's answers which are also strings, the answer for the question which is in the first position of the array @questions is also in the first position but in the @answers, and it's the same for all the questions, so what i want to do is to ask the question to the user, and if he doesn't answer what was expected, he asked to try again. , The error is on this line:
Related Posts Related Posts :
  • how to start two threads (almost) simultaneously?
  • Can I upgrade to the current version of Ruby (2.2.3) on OS X v10.6.8?
  • Iterating over array without returning the array
  • Rspec pass test in ruby testing
  • Why does "23 Dogs" get parsed to 23 november 2015 in pry, but "3 Dogs" gives a parser error?
  • vagrant ssh not working in MobaXterm on Windows
  • What's the most idiomatic substitute for Ruby's missing string#unshift?
  • Ruby remove triple quotes
  • Rspec error in ruby code testing
  • Why doesn't `array.include` [sic] show the correct output
  • Why ruby StringIO does not give different encodings
  • How to convert following curl code to ruby code with restclient
  • Install RHC Client Tools (Openshift) on Windows 10
  • `<top (required)>': uninitialized constant Object::ATM (NameError)
  • How to get response from API after POST
  • Why does Rails-4.2.5 NOT install the expected version of Nokogiri (1.6.7.rc4)
  • How to get a random number with a minimum value
  • Get the names and values of the arguments
  • Issue with Nested Form Create - ActionController::UrlGenerationError in Calls#new
  • Sinatra: modular routes class not recognizing helper methods
  • I solved Project Euler #15 the wrong way. Why did this work?
  • Need a regex that can remove a number and following dot
  • how do i access a param on more than one post or get
  • Issues trying to bootstrap Chef for windows client with knife-windows
  • Ruby: difference between def and define_method
  • Docker container knows rbenv global but not ruby
  • Issue with Routes when implementing a nested form
  • Why are the two randomly generated arrays always the same?
  • Testing program that runs with user input from the console
  • Step Based signal to smooth one - How can I interpolate?
  • How to loop through an array of possible integers, such as from [1,1,1,1] to [1,1,1,2], ... and finally to [6,6,6,6]?
  • Error appearing in bash script when run with LaunchControl
  • How not to have to type "bundle exec" using Bundler binstubs & chruby?
  • Ruby: modules extending/including modules
  • Get path to particular scheme
  • Table.where(x:y).othertable
  • Concatenate procs while retaining context reevaluation capabilities
  • Write a new file with defined function on Ruby
  • Minitest - Tests Don't Run - No Rails
  • How does Ruby differentiate VALUE with value and pointer?
  • Remove certain instance of a specific item from a string
  • Rake, how to create a task with multiple inputs and one output?
  • nil value being assigned in || test
  • How to access element
  • def vs. define_method in Ruby
  • Calculating percentage returns integer
  • Rspec don't show me the its
  • Not able to install any gem including SASS using RubyGems from terminal
  • Match string numbers with Ruby regex
  • Open Editor From Command Line and Fetch Input
  • Find the range in which the number belongs, from a range string
  • output everything between specific string ruby
  • Evaluating multiple rspec expectations with cucumber
  • devise reset password token invalid
  • Disable Rubocop argument list length
  • Vim's Ruby option is not enabled
  • String#gsub to maintain case?
  • Double splat and default value in method profile
  • Child Classes inheriting included module method from parent classes in Ruby
  • Include another script in Ruby script
  • shadow
    Privacy Policy - Terms - Contact Us © animezone.co