noob:如何在Ruby中获得内置语法助手

Noob: How to get build-in syntax helper in Ruby

本问题已经有最佳答案,请猛点这里访问。

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

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

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

子问题:还有.upcase和.capitalize之间的区别吗?


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

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

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

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

any difference between .upcase and .capitalize?

是的。如下所示:

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

String#capitalize :-
Returns a copy of str with the first character converted to uppercase and the remainder to lowercase.

String#upcase :-
Returns a copy of str with all lowercase letters replaced with their uppercase counterparts.


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

1
2
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?]

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