Accessing the contents of an Array containing a hash in Ruby [closed] - ruby

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I am new to ruby and trying out some examples.I have the array below that contains a hashmap.
f = [{"qty"=>"5", "unit"=>"kgs", "item"=>"sugar", "cost"=>"400", "salestax"=>"0.0"}]
I want to print out some thing like this
5 kgs of sugar : 400 at a tax of 0.0(if you notice the content is from the hashset)
I've tried some thing like:
f.each
{
|m| puts m for u in m |qty,unit,item,cost,salestax| puts "#{qty} #{unit} of #{item} : #{cost} #{salestax}"
}
but its not giving me what I want.

f.each do |hash|
puts "#{hash['qty']} #{hash['unit']} of #{hash['item']}: #{hash['cost']} at a tax of #{hash['salestax']}."
end
Seems like that is what you want.

Another way
f.each { |hash| puts "%s %s of %s : %s at a tax of %s" % hash.values }

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

How can I produce one whole string from iteration on array of arrays 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 array of arrays looking something like this :
arr = [[f,f,f,f,f], [f,f,t,f,f], [f,t,f,t,f]]
and am I outputing it formatted on the console like this:
arr.each {|a| puts a.join.gsub('t','<b></b>').gsub('f','<i></i>')}
and it generates something like this:
<i></i><i></i><i></i><i></i><i></i>
<i></i><i></i><b></b><i></i><i></i>
<i></i><b></b><i></i><b></b><i></i>
but it is only in the output. I am wondering how I can assign it to a string? With the new lines and everything, exactly the way it looks,
a= [["f","f","f","f","f"], ["f","f","t","f","f"], ["f","t","f","t","f"]].map do |arr|
arr.join.gsub(/[ft]/) do |x|
if x =~ /f/
'<i></i>'
elsif x =~ /t/
'<b></b>'
end
end
end.join("\n")
puts a
# >> <i></i><i></i><i></i><i></i><i></i>
# >> <i></i><i></i><b></b><i></i><i></i>
# >> <i></i><b></b><i></i><b></b><i></i>

Any good way of checking if a json object is a subset of another one in Ruby? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
By a is a json subset of b, I mean
For object, b has all the key-value pairs as in a.
For array, b has the same size as a, the order doesn't matter though
{"one":1}.should be_subset_json({"one":1,"two":2})
[{"one":1}].should_NOT be_subset_json([{"one":1},{"two":2}])
[{"two":2},{"one":1}].should be_subset_json([{"one":1},{"two":2}])
[{"id":1},{"id":2}].should be_subset_json([{"id":2, "name":"b"},{"id":1,"name":"a"}])
Just implementing your spec there seems to work.
require 'json'
def diff_structure(a, b)
case a
when Array
a.map(&:hash).sort == b.map(&:hash).sort
when Hash
a.all? {|k, v| diff_structure(v, b[k]) }
else
a == b
end
end
RSpec::Matchers.define :be_subset_json do |expected|
match do |actual|
diff_structure JSON.parse(actual), JSON.parse(expected)
end
end
describe "Data structure subsets" do
specify { '{"one":1}'.should be_subset_json('{"one":1,"two":2}') }
specify { '[{"one":1}]'.should_not be_subset_json('[{"one":1},{"two":2}]') }
specify { '[{"two":2},{"one":1}]'.should be_subset_json('[{"one":1},{"two":2}]') }
specify { '{"a":{"one":1}}'.should be_subset_json('{"a":{"one":1,"two":2}}') }
end
# Data structure subsets
# should be subset json "{\"one\":1,\"two\":2}"
# should not be subset json "[{\"one\":1},{\"two\":2}]"
# should be subset json "[{\"one\":1},{\"two\":2}]"
# should be subset json "{\"a\":{\"one\":1,\"two\":2}}"
# Finished in 0.00172 seconds
# 4 examples, 0 failures

How to use code block 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 8 years ago.
Improve this question
I have the following code
animals=['lion','tiger','zebra']
animals.each{|a| puts a}
I wanted to print only tiger in this array for that I wrote something like this
animals.each{|a| if a==1 puts animals[a]}
But it's not working why?
You can play with enumerable like this:
animals.select{ |a| a == 'tiger' }.each{ |a| puts a }
The wrong you did in your case:-
animals.each{|a| if animals[a]==2 puts a}
inline if statement you put in a wrong way.
#each passes element of the array,not the index. So animals[a] will not work. It will throw error as no implicit conversion of String into Integer (TypeError).
Do this as below using Array#each_index
animals=['lion','tiger','zebra']
animals.each_index{|a| puts animals[a] if animals[a] == 'tiger' }
# >> tiger
Maybe you are looking for this
animals.each_with_index{|animal, index| puts animal if index==1}
Please not that "tiger" occurs at index 1 and not 2.
you can simply do this
animals.fetch(animals.index('tiger')) if animals.include? 'tiger'
or
animals[animals.index('tiger')] if animals.include? 'tiger'

How to split a Number to Natural Numerals in Ruby [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
for example:
input: 15
output:
15 = 1+2+3+4+5
15 = 4+5+6
15 = 7+8
input: 4
output: cannot split
Here's one way:
def natural_numerals(value)
results = []
(1..value-1).each {|i| (i..value-1).each {|j| results << (i..j).to_a.join("+") if (i+j)*(j-i+1)/2 == value}}
if results.empty? then nil else results end
end
output1 = natural_numerals(15)
output2 = natural_numerals(4)
puts output1.inspect #=> ["1+2+3+4+5", "4+5+6", "7+8"]
puts output2.inspect #=> nil

Resources