简体   繁体   中英

Arguments to Methods in Ruby

The lesson video & text give examples like this: "ohmy".concat("gosh"(upcase)) . I get that the objects are strings, the method takes arguments which are a method within a method.

But then the exercise is like this: center(integer) , which takes an integer as an argument and centers the string within that many spaces, which makes no sense. I've only seen words in the string class and numbers in the fixnum and float classes and to my knowledge, an integer is a number.

And no idea how I'm supposed to make center(integer) into something like the example "ohmy".concat("gosh"(upcase)) .

If possible, I need an example of how to apply these two exercises.

  1. center(integer) # takes an integer as an argument and centers the string within that many spaces - make sure the argument is big enough to see how it works

  2. count(string) # takes a string as an argument and counts how many times that string occurs in the original string

The code you provided is not syntactically correct:

> "ohmy".concat("gosh"(upcase))
SyntaxError: (irb):1: syntax error, unexpected '(', expecting ')'
"ohmy".concat("gosh"(upcase))
                     ^
    from /usr/bin/irb:12:in `<main>'

should instead be

> "ohmy".concat("gosh".upcase)
=> "ohmyGOSH"

The "center" method works like this:

> "test".center(10)
=> "   test   "

And the "count" method works like this:

> "test".count("t")
=> 2

Also, note that parentheses are sometimes optional in Ruby, so the following works as well, however the parentheses make it easier to read, IMHO:

> "ohmy".concat "gosh".upcase 
=> "ohmyGOSH"
> "test".center 10
=> "   test   "
> "test".count "t"
=> 2

Please let me know if that doesn't make sense and I can try to clarify better.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM