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

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.

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] }

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 define a method which arguments have no type 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
If I defined a method:
def weird_method(first_argument, second_argument)
#code here
end
so this way I can pass arguments like : 1, :digit, 'some', "more"(Fixnum, Symbol, String etc.) , BUT what If I wanted to pass just this: argument1, argument2 , I mean values that have no type and look like local variables but they actually are not. How can I accept them somehow and use them in the method body?
PS: I need it for implementing a small DSL that could do that kind of stuff in the .isntance_eval when blok is passed
Something.with_method do
sum 1, 2 #(I can implement it)
play volleyball #(I can NOT implement it)
swim further #(I can NOT implement it)
eat "a lot" #(I can implement it)
end
EDIT:
Everything could go on the palce of volleyball and further. I am just gave an example. sum, play, swim, eat are methods defined in the Something class.
Symbols exist for exactly the purpose you're talking about here: They're values that just evaluate to themselves. The symbol :volleyball is the symbol :volleyball and that is all it will ever be. It has no other value or meaning.
If you just want it to read differently for aesthetic purposes, your best bet would probably be to define methods that return the appropriate symbol (e.g. def volleyball() :volleyball end). But this seems unidiomatic.
If you really want people to be able to send just about anything that isn't already a method, you could implement a method_missing along the lines of def method_missing(m, *args) m.to_sym end. But I really find this design awkward in most contexts I can think of.
class Something
attr_reader :callstack
def initialize
#callstack = {}
end
def self.with_method &block
self.new.instance_exec &block
end
def method_missing method, *params
params.empty? ? method : callstack[method] = params
end
end
Something.with_method do
sum 1, 2
play volleyball
swim further
eat "a lot"
puts callstack # => {:sum=>[1, 2], :play=>[:volleyball], :swim=>[:further], :eat=>["a lot"]}
end
Does this help?
You must pass objects as method arguments. What functionality are you trying to accomplish by passing arbitrary non-defined names? You could always pass them as a string and then use the string to use the text inside the method.
ex.
def self.methodname(arg1, arg2)
arg1 = arg2
end
Class.methodname("greeting","hello")
would set the variable greeting equal to 'hello'

Ruby print hash key and value [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'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.

Is there a shortcut for assigning some variable with the return value of a method that's used on it 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 often do the following:
#value = #value.some_method
But isn't there a shorter syntax for that in ruby? Some methods offer bang equivalents, but sadly not all...
For iterations one can use:
i += 1
Is that, or something similar, also available for my code snippet above?
There's nothing that does this in a shorter way.
To be fair, it is an unusual pattern, and while not especially rare, would lead to confusion if there was an operator like:
#value .= some_method
How is that even supposed to be parsed when reading?
As the Tin Man points out, in-place operators are really what are best here.
You cannot do that taking the actual variable as the receiver because there is no way to get to the name of the variable. Instead, you need to use the name of the variable like this:
class A
attr_accessor :value
def change_to_do_something name
instance_variable_set(name, "do something")
end
end
a = A.new
a.value = "Hello"
p a.value
# => "Hello"
a.change_to_do_something(:#value)
p a.value
# => "do something"

Resources