ruby - iterate through a hash containing key/array value pairs, and iterate through each value
Pretty simple, really:
hash.each do |name, values|
values.each do |value|
# ...
end
end
You can do whatever you want with name
and value
at the lowest level.
How to iterate over an array of hashes in Ruby and return all of the values of a specific key in a string
You can use Enumerable#map for this:
p foods.map { |f| f[:name] }
The code you tried to use did not produce any output or create any objects, and it was not necessary to use a second loop to access a single element of a hash.
Iterating over a hash response and saving to database
You can just use response["competition"]["id"]
i have a large hash and i want to get specific values in ruby
You are trying to do too much all at once with hash_json['days'][0]['hours'][0]['datetime]
. I suggest breaking this into smaller pieces. For example do days = hash_json['days']
. Now you have a variable with simpler structure. In this case it is a list. You can get the first element with days[0]
or loop over the list with days.each
or days.map
. I suggest you read about each
and map
to learn what they are good for and how they work.
Iterating through two arrays to make a hash in Ruby
I suggest to slice the values array on the keys array length, and then just map them into an array of hashes. For example:
sliced_values = Data_examples.each_slice(Array_headers.length)
result = sliced_values.map { |slice| Array_headers.zip(slice).to_h }
You will never get a single hash as result, because you'll have collision on the keys and, then, only the last result will be returned, since it overwrites the previous ones. Remember that hash keys are unique in Ruby.
How do I loop over a hash of hashes?
Value is a Hash to so you need iterate on it or you can get only values:-
h.each do |key, value|
puts key
value.each do |k,v|
puts k
puts v
end
end
or
h.each do |key, value|
puts key
value.values.each do |v|
puts v
end
end
Ruby Iterating over an array and find match in an hash and replace the element in array
I understand from the kata that letters are to be separated by one space and words by three spaces.
As a first step I will two changes to the hash morse_dict
: remove the key ' '
; and add key-value pairs for some punctuation characters. The space character key is not needed; the need for punctuation codes is discussed in the kata.
PUNCTUATION = { "."=>".-.-.-", ","=>"--..--", "?"=>"..--..", "!"=>"-.-.--" }
ALPHA_TO_MORSE = dict.reject { |k,_| k == " " }.merge(PUNCTUATION)
#=> {"a"=>".-", "b"=>"-...", "c"=>"-.-.", "d"=>"-..", "e"=>".", "f"=>"..-.",
# "g"=>"--.", "h"=>"....", "i"=>"..", "j"=>".---", "k"=>"-.-", "l"=>".-..",
# "m"=>"--", "n"=>"-.", "o"=>"---", "p"=>".--.", "q"=>"--.-", "r"=>".-.",
# "s"=>"...", "t"=>"-", "u"=>"..-", "v"=>"...-", "w"=>".--", "x"=>"-..-",
# "y"=>"-.--", "z"=>"--..", "1"=>".----", "2"=>"..---", "3"=>"...--",
# "4"=>"....-", "5"=>".....", "6"=>"-....", "7"=>"--...", "8"=>"---..",
# "9"=>"----.", "0"=>"-----", "."=>".-.-.-", ","=>"--..--", "?"=>"..--..",
# "!"=>"-.-.--"}
I obtained the Morse codes for the punctuation characters from the Morse Code Wiki. Additional punctuation characters could be added if desired.
The hash ALPHA_TO_MORSE
is used in encoding text. The inverse of this hash is needed for decoding messages in Morse code. Also needed for decoding is the key value pair "...---..."=>"sos"
.
MORSE_TO_ALPHA = ALPHA_TO_MORSE.invert.merge("...---..."=>"sos")
#=> {".-"=>"a", "-..."=>"b", "-.-."=>"c", "-.."=>"d", "."=>"e", "..-."=>"f",
# "--."=>"g", "...."=>"h", ".."=>"i", ".---"=>"j", "-.-"=>"k", ".-.."=>"l",
# "--"=>"m", "-."=>"n", "---"=>"o", ".--."=>"p", "--.-"=>"q", ".-."=>"r",
# "..."=>"s", "-"=>"t", "..-"=>"u", "...-"=>"v", ".--"=>"w", "-..-"=>"x",
# "-.--"=>"y", "--.."=>"z", ".----"=>"1", "..---"=>"2", "...--"=>"3",
# "....-"=>"4", "....."=>"5", "-...."=>"6", "--..."=>"7", "---.."=>"8",
# "----."=>"9", "-----"=>"0", ".-.-.-"=>".", "--..--"=>",",
# "..--.."=>"?", "-.-.--"=>"!""...---..."=>"sos"}
One more hash is needed to deal with cases where the message "sos"
(or "SOS"
--Morse code is case insensitive), or "sos"
followed by a punctuation character (e.g., "sos!"
) is to be encoded.1 See the Wiki.
SOS_WITH_PUNCTUATION = PUNCTUATION.each_with_object({}) { |(k,v),h|
h["sos#{k}"] = "...---... #{v}" }.merge('sos'=>"...---...")
#=> {"sos."=>"...---... .-.-.-", "sos,"=>"...---... --..--",
# "sos?"=>"...---... ..--..", "sos!"=>"...---... -.-.--", "sos"=>"...---..."}
The encoding and decoding methods follow. encode
checks to see if each word in the string is a key in the hash SOS_WITH_PUNCTUATION
. If it is, the value of key is the Morse code for the word; else, the word is divided into letters and each letter is translated into Morse code.
def encode(str)
str.strip.downcase.split.map do |word|
if SOS_WITH_PUNCTUATION.key?(word)
SOS_WITH_PUNCTUATION[word]
else
word.each_char.map { |c| ALPHA_TO_MORSE[c] }.join(' ')
end
end.join (' ')
end
def decode(morse)
morse.strip.split(/ {3}/).map do |word|
word.split.map { |c| MORSE_TO_ALPHA[c] }.join
end.join(' ')
end
We can now try out these two methods.
str = " Is now the time for you, and 007, to send an SOS?"
morse = encode str
#=> ".. ... -. --- .-- - .... . - .. -- . ..-. --- .-. -.-- --- ..- --..-- .- -. -.. ----- ----- --... --..-- - --- ... . -. -.. .- -. ...---... ..--.."
decode morse
#=> "is now the time for you, and 007, to send an sos?"
1 It would be simpler to have a pre-processing step that would convert, say, "sos."
to "sos ."
, but when the resulting Morse code were decoded there would be a space between "sos"
and "."
. I suppose that cryptographers could deal with that, but I've chosen to avoid the insertion of the space.
Related Topics
Error: While Executing Gem ... (Gem::Filepermissionerror)
How to Call Methods Dynamically Based on Their Name
Ruby: How to Post a File Via Http as Multipart/Form-Data
How to Get the Name of the Calling Method
Ruby - Parameters by Reference or by Value
Why Does Installing Nokogiri on MAC Os Fail With Libiconv Is Missing
Can't Install Rmagick 2.13.1. Can't Find Magickwand.H.
Is There a Clean Way to Avoid Calling a Method on Nil in a Nested Params Hash
Is There a Reason That We Cannot Iterate on "Reverse Range" in Ruby
Is It Good Style to Explicitly Return in Ruby
Why Isn't the Eigenclass Equivalent to Self.Class, When It Looks So Similar
I Don't Understand Ruby Local Scope
Why Is This Rmagick Call Generating a Segmentation Fault
Double Colons Before Class Names in Ruby