Ruby print hash key and value [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 9 years ago.
Improve this question
I'm trying to print key : value
Currently I keep getting errors when I try to run my codes.
The code:
output.each do |key, value|
puts key + ' : ' + value
end
I can not figure out a way to do this on the same line. I've tried various implementations, like using the << symbol. I've also played around with print, using multiple puts statements, and appending both values into a string and printing that.

Depending on the contents of your Hash, you might need to convert the key to a string since it might be a symbol.
puts key.to_s + ' : ' + value
Or, what I would suggest doing, use string interpolation:
puts "#{key}:#{value}"
The reason you are getting an error, if key is indeed not a string, is because it is trying to call the method + on whatever key is. If it does not have a + method, you will get an error.

Related

TypeError Parsing Ruby Array of Hashes [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I have an Array of Ruby Hashes that I'm trying to iterate so that I can parse values by key.
forms = {"forms":[{"id":123,"name":"John","created_at":"2021-11-23T21:41:17.000Z"},{"id":456,"name":"Joe","created_at":"2021-11-21T05:17:44.000Z"}]}
forms.each do |form|
puts form ## {:id=>123, :name=>"John", :created_at=>"2021-11-23T21:41:17.000Z"}
puts form["id"]
end
This yields the following error:
main.rb:4:in `[]': no implicit conversion of String into Integer (TypeError)
I'm admittedly a big Ruby noob, but can't figure this out. I've also tried puts form[:id] and puts form[":id"] to no avail.
Note: I don't have any control over the Array of Hashes that's being assigned to the forms variable. It's what I get back from an external API call.
Your forms is a Hash. If you do each on Hash it passes to the block each key & value pair.
forms.each do |key, value|
p key # => :forms
p value # => [{....}]
p value.map { |v| v[:id] }
end
There's also this, in case the forms always has the forms key (doesn't change)
forms[:forms].map { |v| v[:id] }

Attempting to add line breaks in Ruby to_s message [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
In Pragmatic Programmer's Ruby book, they're using to_s to clean up the output. Their output ends up looking like:
Name: UserName, Address: UserAddress, Phone: UserPhone, EMail: UserEmail
They don't have any line breaks, and I'm attempting to add them to mine using \n within the to_s definition:
class PersonalInformation
def initialize (fullname, address, phonenumber, emailaddress)
#fullname = fullname
#address = address
#phonenumber = phonenumber
#emailaddress = emailaddress
end
def to_s
"Name: #{#fullname}\n, Address: #{#address}\n, Phone: #{#phonenumber}\n, EMail: #{#emailaddress}\n"
end
end
info1 = PersonalInformation.new('UserName', 'UserAddress', 'UserPhone', 'UserEmail')
p info1
but I'm not having any luck getting the output to display the way I want, and it doesn't appear that to_s is doing what I expect it to anyway. Mine looks like:
#<PersonalInformation:0x00000002d0e600 #fullname="UserName", #address="UserAddress", #phonenumber="UserPhone", #emailaddress="UserEmail">
A) What do I need to do to make to_s display the way I expect?
B) How do I go about getting line breaks into the output message?
p calls Object#inspect method, not to_s.
You need to call to_s explicitly, or use methods that call to_s. For example, print, puts, printf with %s format.
A) You don't need anything extra. It already displays the way you want.
B) As you did, putting "\n" works.

Why is this variable undeclared but still working? [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'm a beginner & just started to learn ruby through Codecademy. I understand this will be a very simple question. Why are we declaring answer2 in this code? Wouldn't they both be equal?
print "This is my question?"
answer = gets.chomp
answer2 = answer.capitalize
answer.capitalize!
Thanks.
They're trying to teach you the difference between capitalize and capitalize!. The first doesn't modify the string but rather returns a modified copy of it. While the latter (with a bang ! mark) modifies the string itself.
So to further explain the example above, consider the following:
print "This is my question?"
answer = gets.chomp
answer2 = answer.capitalize
puts "answer= " + answer + ", while answer2= " + answer2
answer.capitalize!
puts "now answer= " + answer
So if we execute the previous code and enter foobar when it prompts, the output will be:
This is my question?foobar
answer= foobar, while answer2= Foobar
now answer= Foobar
Generally, methods in ruby don't modify the objects that called them, but rather return a modified copy. So in some_object.some_method, the some_method method is not going to change some_object but will return a copy of it with some modifications. Alternatively, methods with at bang ! mark change the objects that called them. So some_object.some_method! will change some_object itself.

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.

Resources