Return Values Were Not Extracted in Ruby

Return values were not extracted in Ruby

Your main problem is -

 departments, classifications, types = [["-- select one --"]] * 3

changed it to -

departments, classifications, types = Array.new(3) { ["-- select one --"] }

Lets debug it :-

([[]] * 3).map(&:object_id) # => [72506330, 72506330, 72506330]

but

Array.new(3) { [] }.map(&:object_id) # => [76642680, 76642670, 76642520]

You can see, that all the inner objects are basically same object. Basically you have created an array of array, say a, where all the element arrays are same object. Thus if you have modified, say a[0], you can see the same change when you would inspect a[1] or a[2]. But if you do create the same array of array, a as , Array.new(3) { [] }, then each inner element array of a, will be different object. Thus if you say modify a[0], then a[1] and a[2] will be intact.

Worth to read Common gotchas.

Substring extraction issues with regex in Ruby

If there's a capturing group in pattern, String#scan returns array of arrays to express all groups.

For each match, a result is generated and either added to the result
array or passed to the block. If the pattern contains no groups, each
individual result consists of the matched string, $&. If the pattern
contains groups, each individual result is itself an array containing
one entry per group
.

By removing capturing group or by replacing (...) with non-capturing group (?:...), you will get a different result:

string = "Example string with 3 numbers, 2 commas, and 6,388 other values ..."
string.scan(/\d{1,3}(?:,\d{1,3})*/) # no capturing group
# => ["3", "2", "6,388"]

How to extract a value from a hash

The keys method returns an array of the key names; it doesn't return the values.

Given these inputs:

json = '{"user1":{"about_you":"jjhj","age":18,"email":18},"user2":{"about_you":"jjhj","age":18,"email":18},"user3":{"about_you":"jjhj","age":18,"email":18}}'
data_hash = JSON.parse(json)

Try just iterating over the hash's keys and values:

data_hash.each { |k,v| puts v['email'] }

Or if you prefer:

data_hash.each do |k,v|
puts v['email']
end

Each returns:

18
18
18

Extract values from Ruby data hash and concatenate values into single continuous String

As your input (h) is a hash that can contain hashes in its values, you can implement the method to extract the strings from the values using recursion:

input = {a: "da", b: {c:"test", e: {f: "bird"}}, d:"duck"}

def extract_values_from_hash(input)
return input unless input.is_a?(Hash)

input.flat_map { |_, v| extract_values_from_hash(v) }
end

extract_values_from_hash(input).join
# datestbirdduck

What it does is to receive the hash (input) from which extract the values adding a guard clause - as the base case, which returns the argument the method was called with if it's a hash object, otherwise it flattens and map the object invoking the method itself. This way you extract every value from the initial method argument.

Notice this extracts anything that's in the input that's not directly a hash, if you happen to have an object like this:

{a: "da", b: {c:"test", e: {f: "bird"}}, d:"duck", g: 1, h: [{i: "hola"}, {j: "chao"}]}

The result would be:

"datestbirdduck1{:i=>\"hola\"}{:j=>\"chao\"}"

Extracting recurring elements from array (Bad Value for Range Error)

There are a couple of issues here. From your example array it looks like the ending element is ':/desc' rather than ':/desc:' (i.e. no trailing :). That could just be a typo in the question though.

The main issue is that after removing the 2 slices the array will not be empty (it will still contain the "hello" from before the first start_element. This means that the array.any? condition will still be true when find_index(start_element) isn't going to find a matching element. In this case find_index will return nil, leading to a no implicit conversion from nil to integer when trying to use slice!.

If you know that your data will always contain start_element and end_element in matched pairs then one approach would be:

while start_index = array.find_index(start_element)
end_index = array.find_index(end_element)
final_array << array.slice!(start_index..end_index)
end

When faced with this kind of error in the future, some trusty puts debugging will help, in this case checking the 2 indexes and the remaining contents of the array:

while array.any?
start_index = array.find_index(start_element)
end_index = array.find_index(end_element)
puts "#{start_index}..#{end_index}"
final_array << array.slice!(start_index..end_index)
puts array.inspect
end

1..5
["hello", ":desc:", "claire", "caca", "concise", "test", ":/desc"]
1..6
["hello"]
..
TypeError: no implicit conversion from nil to integer
from (pry):146:in `slice!'

Extract value from optional nested object

I would use Hash#values_at and then pick the value from the one hash that was returned:

message
.values_at(*[:message, :callback, :picture, ...])
.compact
.first[:value]


Related Topics



Leave a reply



Submit