Access each key in array of hashes [closed] - ruby

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have the following array of hashes.
[{"comments_count"=>3, "like_count"=>341, "media_type"=>"IMAGE", "media_url"=>"https://url1.jpg", "permalink"=>"https://www.url.com", "timestamp"=>"2018-09-16T11:29:09+0000", "id"=>"17881817992270180"}, {"comments_count"=>1, "like_count"=>209, "media_type"=>"IMAGE", "media_url"=>"https://url2.jpg", "permalink"=>"https://www.url2.com", "timestamp"=>"2018-09-15T18:38:59+0000", "id"=>"17950602214183642"}]
I want to loop over each media_url like this:
Array.each do |media|
media.media_url
end
But I get the following error:
undefined method `media_url' for Hash:0x00007fb987684d48

Use [] to access hash values - it's not JS :)
a = [{"comments_count"=>3, "like_count"=>341, "media_type"=>"IMAGE", "media_url"=>"https://url1.jpg", "permalink"=>"https://www.url.com", "timestamp"=>"2018-09-16T11:29:09+0000", "id"=>"17881817992270180"}, {"comments_count"=>1, "like_count"=>209, "media_type"=>"IMAGE", "media_url"=>"https://url2.jpg", "permalink"=>"https://www.url2.com", "timestamp"=>"2018-09-15T18:38:59+0000", "id"=>"17950602214183642"}]
a.each {|h| h['media_url'] }

Alternatively, you could refer to the values of specific key, by using .fetch() method on the Hash.
arr = [{"comments_count"=>3, "like_count"=>341, "media_type"=>"IMAGE", "media_url"=>"https://url1.jpg", "permalink"=>"https://www.url.com", "timestamp"=>"2018-09-16T11:29:09+0000", "id"=>"17881817992270180"}, {"comments_count"=>1, "like_count"=>209, "media_type"=>"IMAGE", "media_url"=>"https://url2.jpg", "permalink"=>"https://www.url2.com", "timestamp"=>"2018-09-15T18:38:59+0000", "id"=>"17950602214183642"}]
arr.each {|h| h.fetch('media_url') }
in case key has not been found in some of the hashes, can specify default value:
arr.each {|h| h.fetch('media_url') { 'https://default_url.jpg' } }
To directly return an output as an Array of links, you can simply use .map() instead:
arr.map {|h| h.fetch('media_url') { nil } }

Related

How do I iterate over this Hash in Ruby? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last year.
Improve this question
[:sha,"string"]
[:node_id,"dsd"]
[:stats,{:total=>122},:additions=>23],:deletions=>72}]
[:files,[{:sha=>"456"},:filename=>"456"],{:sha=>"123"},:filename=>"123"]]
I want to access the content of files sha and stats.
client.commit("healtheintent/hcc_reference_service","3a3c56babbc1c77323d178303fa06f8d11e1133d").each do |key,value|
if("#{key}"=="files")
puts ("#{value}")
end
end
Now the values returns the entire content inside the files
Similarily, How do I access the stats
How to iterate over the hash in general
hash = { a: 1, b: 2, c: 2 }
hash.each do |key, value|
if key == :a
puts "a is #{value}"
else
puts "It is not a, it's #{key}"
end
end
Also you can iterate over the keys only or over the values only using each_key or each_value methods

updating array based on symbols Ruby [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
How does one update the array based on symbols? Like
data = []
string = "Hello"
if( !data.include? string )
count += 1
data.insert(-1, {
label: string,
value: count,
})
else
#logic to change count value if string is encountered again
end
I was thinking of finding the index where the string lies and then delete that to insert another updated values at that index. Is this the right approach?
Just use find to get the match, provided its the only one in the array. You can use select to get multiple matches. After that just update the count
As your example is taken out of context and contains errors, I've taken a liberty to make a more complete example.
data = []
strings = ["Hello", "Bye", "Hello", "Hi"]
strings.each do |string|
hash = data.find{ |h| h[:label] == string }
if hash.nil?
data << {label: string, value: 1}
else
hash[:value] += 1
end
end

How to use the .any? method in ruby to return true if there is a string in the array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am trying to create an any_strings? method that takes an array and returns true if there is a string in the array. For example:
a = [ 1, 2, 3, "string" ]
any_strings?(a)
#=> true
b = [ 1, 2, 3, 4 ]
any_strings?(b)
#=> false
Define any_strings? as follows:
def any_strings?(a)
end
Am I supposed to use the is_a? method, I am quite confused with how exactly you use 2 block methods
Shouldn't be too hard.
def any_strings?(array)
array.any? { |element| element.is_a?(String) }
end
This is rather easy to do in point-free style:
def any_strings?(array)
array.any?(&String.method(:===))
end

Assign hash values in a method [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Say I have this method
def foo(bar1, bar2)
## code
end
How could I implement the code so that, when I call foo('hello', 'world'), the foo method accesses a hash, giving:
{
:bar1 => 'hello',
:bar2 => 'world'
}
Is there a Ruby (Rails?) built in method, or how could I write it?
def foo(bar1, bar2)
names = method(__method__).parameters.map{|e| e[1]}
Hash[names.zip(names.map {|name| eval(name)})]
end
Don't do that. It's ugly and evil. Give me the whole context, you're doing something wrong.
def foo(bar1, bar2)
{bar1: bar1, bar2: bar2}
end
If what Sergio mentions was the intention of the question, then
def foo(bar1, bar2)
Hash[method(__method__).parameters.map{|_, k| [k, eval(k.to_s)]}]
end

Odd string split in ruby? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have this expression "1=2,3=(4=5,6=7)" and I want to create a Hash out of this - 1 => 2, 3 => (4=5,6=7). I can do this in 2 passes. In first pass, I can transform the (.*) to something like (4;5,6;7) and then in 2nd pass do some split.
Any better solutions?
As long as you don't need to worry about nested parentheses, and
anything inside parentheses are to be treated as a plain string:
str = "1=2,3=(4=5,6=7)"
Hash[str.scan(/([^=,]+)=(\([^\)]+\)|[^=,]+)/)]
# => {"1"=>"2", "3"=>"(4=5,6=7)"}
If you need nested hashes, use a recursive method:
def hashify(str)
arr = str.scan(/([^=,]+)=(\([^\)]+\)|[^=,]+)/).map do |key, val|
if val[0] == '(' && val[-1] == ')'
[key, hashify(val[1..-2])]
else
[key, val]
end
end
Hash[arr]
end
hashify "1=2,3=(4=5,6=7)"
# => {"1"=>"2", "3"=>{"4"=>"5", "6"=>"7"}}
Note that this still doesn't handle nested parentheses properly. You would need a proper parser for that.

Resources