-10

解决各种语法问题,例如:

print "What's your fist name?"
first_name = gets.chomp 
put "Your name is #{first_name}!"
undefined method `put' for #<Context:0xbac070>

你能分享一些使用助手的好技巧吗?

子问题:.upcase 和 .capitalize 之间有什么区别?

4

2 回答 2

4

不,是String#downcase。像这样使用它:

lower = "Hello World!".downcase # => "hello world!"

检查类的任何特定方法的另一种方法如下:

"Hello World!".methods.grep(/down/) # => [:downcase, :downcase!]
"Hello World!".methods.grep(/lower/) # => []

.upcase 和 .capitalize 有什么区别?

就在这里。如下所示:

"hello".capitalize # => "Hello"
"hello".upcase # => "HELLO"

String#capitalize:- 返回 str 的副本,其中第一个字符转换为大写,其余字符转换为小写。

String#upcase:- 返回 str 的副本,其中所有小写字母都替换为对应的大写字母。

于 2013-06-22T18:52:37.887 回答
2

OMG 的回答在技术上是正确的,但您应该养成检查对象支持哪些方法的习惯:

irb(main):001:0> "Hello, world!".methods.sort
=> [:!, :!=, :!~, :%, :*, :+, :<, :<<, :<=, :<=>, :==, :===, :=~, :>, :>=, :[], :[]=, :__id__, :__send__, :ascii_only?, :between?, :bytes, :bytesize, :byteslice, :capitalize, :capitalize!, :casecmp, :center, :chars, :chomp, :chomp!, :chop, :chop!, :chr, :class, :clear, :clone, :codepoints, :concat, :count, :crypt, :define_singleton_method, :delete, :delete!, :display, :downcase, :downcase!, :dump, :dup, :each_byte, :each_char, :each_codepoint, :each_line, :empty?, :encode, :encode!, :encoding, :end_with?, :enum_for, :eql?, :equal?, :extend, :force_encoding, :freeze, :frozen?, :getbyte, :gsub, :gsub!, :hash, :hex, :include?, :index, :initialize_clone, :initialize_dup, :insert, :inspect, :instance_eval, :instance_exec, :instance_of?, :instance_variable_defined?, :instance_variable_get, :instance_variable_set, :instance_variables, :intern, :is_a?, :kind_of?, :length, :lines, :ljust, :lstrip, :lstrip!, :match, :method, :methods, :next, :next!, :nil?, :object_id, :oct, :ord, :partition, :prepend, :private_methods, :protected_methods, :public_method, :public_methods, :public_send, :replace, :respond_to?, :respond_to_missing?, :reverse, :reverse!, :rindex, :rjust, :rpartition, :rstrip, :rstrip!, :scan, :send, :setbyte, :singleton_class, :singleton_methods, :size, :slice, :slice!, :split, :squeeze, :squeeze!, :start_with?, :strip, :strip!, :sub, :sub!, :succ, :succ!, :sum, :swapcase, :swapcase!, :taint, :tainted?, :tap, :to_c, :to_enum, :to_f, :to_i, :to_r, :to_s, :to_str, :to_sym, :tr, :tr!, :tr_s, :tr_s!, :trust, :unpack, :untaint, :untrust, :untrusted?, :upcase, :upcase!, :upto, :valid_encoding?]

这将帮助您探索哪些方法可供您使用。

于 2013-06-22T18:54:21.207 回答