Using Tuples in Ruby

Using Tuples in Ruby?

OpenStruct?

Brief example:

require 'ostruct'

person = OpenStruct.new
person.name = "John Smith"
person.age = 70
person.pension = 300

puts person.name # -> "John Smith"
puts person.age # -> 70
puts person.address # -> nil

Does Ruby have a `Pair` data type?

You can also use OpenStruct datatype. Probably not exactly what you wanted, but here is an implementation ...

require 'ostruct'

foo = OpenStruct.new
foo.head = "cabeza"
foo.tail = "cola"

Finally,

puts foo.head
=> "cabeza"

puts foo.tail
=> "cola"

Getting all tuples in Ruby

inp.
map { |i| (0...i).to_a }.
reduce(&:product).
map(&:flatten)

Used operations: Range, Enumerable#map, Enumerable#reduce, Array#product, Array#flatten.

passing tuple to ruby hash

The monster here is the else clause in your original code. If you can get rid of it, then you can make a hash for lookup.

my_hash = {
['windows', nil] => -> { exec_windows },
['redhat', 'pci'] => -> { exec_pci },
['redhat', 'non_pci'] => -> { exec_non_pci }
}

os, env = 'windows', nil

my_hash[[os, env]].call

Note that querying a hash by key requires exact matches, so for example, if your os is 'windows', the env must be nil, otherwise you'll get a NoMethodError telling you that nil has no method named call. You can make this error thrown a little bit earlier by using Hash#fetch

my_hash.fetch([os, env]).call

The other caveat is that you have to define my_hash in the same scope where the job (e.g. exec_pci) is supposed to be called, otherwise you may not be able to call those methods correctly.

Convert string to tuple, hash, or array

Hash[*s[1..-2].gsub('"', '').reverse.sub(',', '|').reverse.split('|')]

Result

{"Doe, John"=>"12345"}

Explain:

s                                 # (\"Doe, John\",12345)
s[1..-2] # remove bracket => \"Doe, John\",12345
.gsub('"', '') # remove double quote => Doe, John,12345
.reverse.sub(',', '|').reverse # make the last , into | => Doe, John|12345
.split('|') # split the string to array => ["Doe, John", "12345"]
Hash[*s] # make the array into hash => {"Doe, John"=>"12345"}

Array of tuples, sum the values when the the first element is the same

data = [[1, 8], [3, 16], [1, 0], [1, 1], [1, 1]]
data.each_with_object({}) { |(k, v), res| res[k] ||= 0; res[k] += v }

gives

{1=>10, 3=>16}

there is also inject version although it's not so laconic:

data.inject({}) { |res, (k, v)| res[k] ||= 0; res[k] += v; res }

inject vs each_with_object

Convert Ruby array of tuples into a hash given an array of keys?

If the order of the mapping between the key and pairs should be based on the first element in array2, then you don't need array at all:

array2 = [
["apple", "good taste", "red"],
["lemon" , "no taste", "yellow"],
["orange", "bad taste", "orange"]
]

map = Hash[ array2.map{ |a| [a.first,a] } ]
p map
#=> {
#=> "apple"=>["apple", "good taste", "red"],
#=> "lemon"=>["lemon", "no taste", "yellow"],
#=> "orange"=>["orange", "bad taste", "orange"]
#=> }

If you want to use array to select a subset of elements, then you can do this:

# Use the map created above to find values efficiently
array = %w[orange lemon]
hash = Hash[ array.map{ |val| [val,map[val]] if map.key?(val) }.compact ]
p hash
#=> {
#=> "orange"=>["orange", "bad taste", "orange"],
#=> "lemon"=>["lemon", "no taste", "yellow"]
#=> }

The code if map.key?(val) and compact ensures that there is not a problem if array asks for keys that are not present in array2, and does so in O(n) time.

Find the tuple with the right ID ruby

You could do soemthing like this using ruby select: http://www.ruby-doc.org/core-2.1.1/Enumerable.html#method-i-select

a = [["object1", "stat1"],["object2", "stat2"]]
a.select { |elem| elem.include?("object1") }


Related Topics



Leave a reply



Submit