updating array based on symbols Ruby [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 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

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

I need my API to print a list of titles as well as a full description. I am having trouble getting a list of titles. Any advice? [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 2 years ago.
Improve this question
class RecipePuppyAPI1
URL = "http://www.recipepuppy.com/api/"
def get_recipes
uri = URI.parse(URL)
response = Net::HTTP.get_response(uri)
JSON.parse(response.body)
end
def recipe_titles(json)
recipes = []
json.collect do |recipe|
recipes << recipe["title"]
end
end
end
recipes = RecipePuppyAPI1.new.get_recipes
puts ap recipes.uniq
Your recipe_titles method doesn't return the right thing. collect is used to map 1:1 an input array to an output array, and the output of each iteration is the result.
It looks like you're confusing each, an iterator, with collect, which is a transform operation. You're also declaring an array which isn't used properly, as normally that'd be your return value.
To fix it, remove the temporary variable, strip it down to this:
def recipe_titles(json)
json.collect do |recipe|
recipe["title"]
end
end
Or more generically:
def recipe_fields(json, field)
json.collect do |recipe|
recipe[field]
end
end
Where you can call it like:
recipe_fields(json, 'title')

How can I print out the value of each key in a hash represented by *'s? [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 8 years ago.
Improve this question
Here is my code:
class String
def frequency
chars.each_with_object(Hash.new(0)) do |char, h|
h["#{char.upcase}:"] += 1 if char[/[[:alpha:]]/]
end
end
end
I've tried breaking it down in smaller bit's of code, such as using a .times do loop but I couldn't figure it out
for example:
str = "\*"
h["A:"] = count('a').times do
str
end
Are you trying to do something like:
counts = 'aassssvvvvv'.frequency
counts.each{|key,count| puts key + '*'*count}
# A:**
# S:****
# V:*****
Or if you want to change the key you can do:
counts.each{|key,amount| counts[key] = '*'*amount}

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.

Problems with loops in Ruby Code [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Hey I have an array with numbers in it.
Now I want to divide the value at 17th position of the array by the value at the first position of the array, then the 18th by the second, and so on. The results should build a new array.
Then I want to scan all values of the new array and if two or more successive values are bigger than 1.2, I want to add the result of dividing the first by the last value of that row for all of successive values. If one value is 1.2 and the next for example 0.8, the values of the array should not be changed.
Here is my code:
a = [1,2,3,4,5,9,5,13,14,17,19,23,19,34,46,12,13,45,46,67,78,79]
b = Array.new
c = Array.new
a.each_cons(18) { |c| b.push(c[17]/c[0] }
Do you have an idea how to implement the condition?
I think this will do it, although I selectively interpreted some things from your question. Specifically, in "of that row for all of successive values," does "row" refer to the sliding block from each_cons? Ditto for "all of successive values."
catch (:done) do
for i in 2..b.length do
b.each_cons(i) do |d|
for j in 2..d.length do
d.each_cons(j) do |g|
if g.all? { |g| g > 1.2 }
c = b.map { |f| f + (d[0].to_f/d[i-1].to_f) }
break
end
if !c.empty? then throw :done end
end
end
end
end
end
puts c

Resources