Friday 3 June 2016

Arithmetic and Conversions, String, Array and Hash

Arithmetic and Conversions:

    2.class == Fixnum 
    Fixnum.superclass == Integer 
    Integer.superclass == Numeric 
     
    3.0.class == Float 
    Float.superclass == Numeric 
     
    2/3 == 0 
    2/3.0 # => 0.6666667 
    2 + 3.0 == 5.0 
    "2".to_i + "3.0".to_f == 5.0 
     
    10000000000.class == Bignum 
    Bignum.superclass == Integer 
     
    2 + "3" # => TypeError: String can't be coerced into Fixnum   

String Class:

    "ruby".upcase + " " + "rails".capitalize # => RUBY Rails 
     
    "time is: #{Time.now}\n second line" 
     
    'no interpolation "here" #{Time.now}' # => no interpolation "here" #{Time.now} 
     
    "I" << "Go" << "Ruby" # => IGoRuby 
     
    %Q{"C" and "Java"} # => "C" and "Java" 
     
    %q{single 'quoted'} # => single 'quoted' 
     
    <<-END 
        A here 
        document at #{Time.now} 
    END  

Array Class:

    a = ["Ruby", 99, 3.14] 
    a[1] == 99 
    a << "Rails" 
    ['C', 'Java', 'Ruby'] == %w{C Java Ruby} 
    [1, 2, 3].map { |x| x**2 }.join(", ") 
    [1, 2, 3].select { |x| x % 2 == 0 } 
    [1, 2, 3].reject { |x| x < 3 } 
    [1, 2, 3].inject { |sum, i| sum + i } 
     
    [1, [2, 3]].flatten! # => [1, 2, 3] 
     
    %w{C Java Ruby}.include?("C") # => true 
     
    fruits = ['apple', 'banana'] 
    fruits += ['apple'] unless fruits.include?('apple') 
    [1, 3, 5] & [1, 2, 3] # (intersection) => [1, 3] 
    [1, 3, 5] | [2, 4, 6] # (union) => [1, 3, 5, 2, 4, 6] 
    [1, 2, 3] - [2, 3] # (difference) => [1]   

Hash Class:

h = {:lang => 'Ruby', :framework => 'Rails'} 
h[:lang] == 'Ruby' 
h[:perl] == nil 
puts h.inspect 
env = {"USER" => "peter", "SHELL" => "/bin/bash"} 
env.each {|k, v| puts "#{k}=#{v}" }

Practice this i will get back to you with new concept.
Subscribe this blog for new updates.

No comments:

Post a Comment

My Experience in RUBYCONF INDIA 2016

Hi Readers, Rubyconf India is a global event complementing other RubyConf events across the world. I attended this event held on 19-20 ma...