字符串截取,
英文单词单数复数转换( Agile Web Development with Rails [Chapter 15||||||||||||||Active Support[P251])
ruby 代码
英文单词单数复数转换( Agile Web Development with Rails [Chapter 15||||||||||||||Active Support[P251])
ruby 代码
- string = "Now is the time"
- puts string.at(2) #=> "w"
- puts string.from(8) #=> "he time"
- puts string.to(8) #=> "Now is th"
- puts string.first #=> "N"
- puts string.first(3) #=> "Now"
- puts string.last #=> "e"
- puts string.last(4) #=> "time"
- puts string.starts_with?("No" ) #=> true
- puts string.ends_with?("ME" ) #=> false
- count = Hash.new(0)
- string.each_char {|ch| count[ch] += 1}
- puts count.inspect #=> {" "=>3, "w"=>1, "m"=>1, "N"=>1, "o"=>1,
- "e" =>2, "h" =>1, "s" =>1, "t" =>2, "i" =>2}
- Active Support adds methods to all strings to support the way Rails itself
- converts names from singular to plural, lowercase to mixed case, and so on. A
- few of these might be useful in the average application.
- "cat".pluralize
- puts #=> cats
- "cats".pluralize
- puts #=> cats
- "erratum".pluralize
- puts #=> errata
- "cats".singularize
- puts #=> cat
- "errata".singularize
- puts #=> erratum
- "first_name".humanize
- puts #=> "First name"
- "now is the time".titleize
- puts #=> "Now Is The Time"
ruby 代码
- =begin
- # delete hash key if it not in `arr_need` and it exists in `arr_del` element
- hash={"previous"=>nil, "operateDescription"=>nil, "channel_status"=>["E", "R", "P", "Q"], "next"=>nil, "lastOperator"=>nil}
- arr_need=['previous','operateDescription','channel_status','next','lastOperator'] # fields have in the hash
- arr_del=['lastOperator','next'] # Don't have in the arr_need
- hash_after=StringArray.hsh_delete_if(hash,arr_need,arr_del) => {"previous"=>nil, "operateDescription"=>nil, "channel_status"=>["E", "R", "P", "Q"]}
- =end
- def self.hsh_delete_if(hash,arr_need,arr_del)
- hash.delete_if do |key,value|
- !arr_need.include?(key) or arr_del.include?(key)
- end
- return hash
- end
- =begin
- # delete array value if it not in `arr_need` and it exists in `arr_del` value
- hash=["previous", "operateDescription", "channel_status", "next", "lastOperator"]
- arr_need=['previous','operateDescription','channel_status','next','lastOperator'] # fields have in the hash
- arr_del=['lastOperator','next'] # Don't have in the arr_need
- hash_after=StringArray.arr_delete_if(hash,arr_need,arr_del) => {"previous"=>nil, "operateDescription"=>nil, "channel_status"=>["E", "R", "P", "Q"]}
- =end
- def self.arr_delete_if(array,arr_need,arr_del)
- array.delete_if do |value|
- !arr_need.include?(value) or arr_del.include?(value)
- end
- return array
- end