使用ruby的if / elsif内联语句的语法

时间:2019-05-21 19:55:38

标签: ruby if-statement

可以在行内声明if elsif语句吗?

x > 2 ? "Greater" : "Equal or lower"

if x == 2 
  puts "Equal"
elsif x > 2 
  puts "Greater"
else
  puts "Lower"

3 个答案:

答案 0 :(得分:3)

是的,您可以通过两种方式做到这一点:

  1. 带有分号

    AC.OpenCurrentDatabase("C:\Testing\OvertimeRequest.accdb")
    AC.DoCmd.OutputTo(Access.AcOutputObjectType.acOutputReport, "OT Weekly Report", ".pdf", path & "\" & filename,, "OTDate > # " & Today & " # ",, Access.AcExportQuality.acExportQualityPrint)
    AC.CloseCurrentDatabase()
    
  2. if x == 2; "Equal"; elsif x > 2; "Greater"; else; "Lower"; end

    then

还请记住,if x == 2 then "Equal" elsif x > 2 then "Greater" else "Lower" end 是具有返回值的表达式,例如:

if/unless

val = if x == 2 then "Equal"
      elsif x > 2 then "Greater"
      else "Lower"
      end

答案 1 :(得分:3)

另外三种方式:

(x == 2 && "Equal") || (x > 2 && "Greater") || "Lower"

case x <=> 2 when -1 then "Lower" when 0 then "Equal" else "Greater" end

["Equal", "Greater", "Lower" ][x <=> 2]

答案 2 :(得分:2)

好的,你可以写

// prepare blobs with data of files when load a page
var fileUrls = [...];
var blobs = [];
for(i = 0; i < fileUrls.length; i++) {

    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if(this.readyState == 4 && this.status == 200) {

            var filename = this.responseURL.split('/')[this.responseURL.split('/').length*1-1*1];
            var mimeType = this.getResponseHeader('Content-Type');
            blobs.push([filename, new Blob([this.response], {type: mimeType})]);
        }
    };
    xhttp.open('GET', fileUrls[i], true);
    xhttp.responseType = "arraybuffer";
    xhttp.send();
}

document.getElementsByClassName('.download_all_link')[0].addEventListener('click', function(){

    if(this.id != '') {
        var zip = new JSZip();
        var folder = zip.folder('subfolder');

        for(i = 0; i < blobs.length; i++) {
            folder.file(blobs[i][0], blobs[i][1]);
        }

        zip.generateAsync({type : 'blob'})
            .then(zip_blob => {
                download_all.href = URL.createObjectURL(zip_blob);
            });

        // as we don't know when zip is ready, 
        // we check link href every 500 ms by using recursive function with setTimeout()
        checkHref(this);
    }
});
}

function checkHref(thisLink) {
    setTimeout(function() {

        // when zip is ready we click by the link again to download zip
        if(~thisLink.href.indexOf('blob:')) {
            thisLink.download = 'myfiles.zip';
            thisLink.id = ''; // to prevent zipping again
            thisLink.click(); // to download zip
        } else {
            checkHref(thisLink);
        }
    }, 500);
}

但是我建议您不要编写此类行,因为IMO很难阅读和理解。