zl程序教程

您现在的位置是:首页 >  后端

当前栏目

[Ruby] 1. Expression

ruby expression
2023-09-14 09:00:56 时间
  • Unless to replace if !..?
  • Unless可以理解为"除了"
if ! tweets.empty?
  puts "Timeline:"
  puts tweets
end

//Unless is more intuitive

unless tweets.empty?
    puts "Timeline:"
    puts tweets
end

 

Only nil is falsey

if attachment.file_path != nil
    attachment.post
end

//nil treated as false

if attachment.file_path
    attachment.post
end

 

  • "" treated as "true"
  • 0 treated as "true"
unless name.length  // will never be false
    warn "User name required"
end
  • [] treated as "true"

 

Inline conditionals:

if password.length < 8
    fail "Password too short"
end
unless username
    fail "No user name set"
end


//try inline if / unless


fail "Password too short" if password.length < 8
fail "No user name set" unless username

 

Short-Circuit And

if user
    if user.signed_in?
        # ..
    end
end

// use && instead

if user && user.singed_in?
    #..
end

 

Short-Circuit Assignment

result = nil || 1 --->1

result = 1 || nil --->1

result = 1 || 2   --->1

 

Deafult values - "OR"

tweets = timeline.tweets
tweets = [] unless tweets

//if nil, default to empty array

tweets = timeline.tweets || []

 

Short-circuit evaluation

def sign_in
    current_session || sing_user_in
end

#sign_user_in: not evaluated unless current session is nil
# but consider whether if / then would be more legile!

 

Conditional Assisgnment

i_was_set = 1
i_was_set ||= 2  #check if i_was_set or not first

puts i_was set
# --> 1


-------------

i_was_not_set ||= 2
puts i_was_not-set 
# ---> 2

 

options[:country] = 'us' if options[:country].nil?

#use conditional assignment

option[:country] ||= 'us'

 

Conditional return values:

if list_name
    options[:path] = "/#{user_name}/#{list_name}"
else 
    options[:path] = "/#{user_name}"
end

#assign the value of the if statement


options[:path] = if list_name
    "/#{user_name}/#{list_name}"
else
    "/#{user_name}"
end

 

In method: automaticlly return the value:

def list_url(user_name, list_name)
    if list_name
        http://answer.com"
    else
        "http://question.com"
    end
end

 

Case statement value:

client_url = case client_name
    when "web"
        "http://twitter.com"
    when "Facebook"
        "http://www.facebook.com"
    else
        nil
end

 

Case - When / then

tweet_type = case tweet.status
    when /\A@\w+/ then :mention
    when /\Ad\s+\w+/ then :direct_message
    else                              :public
end