Ruby迭代器块焦点到参数?

时间:2015-10-29 21:04:59

标签: ruby foreach parameters params

我有一个大的迭代器,我需要将一个循环计数整数插入到我的Sinatra帖子捕获的参数中的参数中。

我无法弄清楚如何在循环中扩充参数(:s_fieldname_i)。我想引用上一个i中的循环计数。为了在这里展示挑战,我简化了循环:

    1.upto(@count) do |i|
        @f += " <label for=\"" + params[:s_fieldname_i] + "\">" + params[:s_fieldname_i.capitalize!] + "</label>\n"
    end

我尝试了一些字符串插值(#{i}),但这只是混淆了它。我确信有办法完成这项工作。

3 个答案:

答案 0 :(得分:1)

在这种情况下,您应该尝试避免字符串连接,因为如果任何一个参数值在某个时刻变为nil,它将会爆炸您的应用。

尝试使用字符串插值,我认为你正在寻找这样的东西:

1.upto(@count) do |i|
  @f += "<label for='#{params[:s_fieldname_i]}'> #{params[:s_fieldname_i.capitalize!]}</label>\n"
end

答案 1 :(得分:1)

有时,将其分解为单独的变量可以使其更容易。

1.upto(@count) do |i|
    fieldname = "s_fieldname_#{i}".to_sym
    @f += " <label for=\"" + params[fieldname] + "\">" + params[fieldname.capitalize!] + "</label>\n"
end

答案 2 :(得分:0)

 private void convertAudio(String filename) throws IOException {

    String outputpath =Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).getPath()+"/converted.m4a";
    // Set up MediaExtractor to read from the source.

    MediaExtractor extractor = new MediaExtractor();
    extractor.setDataSource(filename);


    int trackCount = extractor.getTrackCount();

    // Set up MediaMuxer for the destination.
    MediaMuxer muxer;
    muxer = new MediaMuxer(outputpath, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);
    // Set up the tracks.
    HashMap<Integer, Integer> indexMap = new HashMap<Integer, Integer>(trackCount);
    for (int i = 0; i < trackCount; i++) {
        extractor.selectTrack(i);
        MediaFormat format = extractor.getTrackFormat(i);
        format.setString(MediaFormat.KEY_MIME, MediaFormat.MIMETYPE_AUDIO_AMR_NB);

        int dstIndex = muxer.addTrack(format);
        indexMap.put(i, dstIndex);
    }
    // Copy the samples from MediaExtractor to MediaMuxer.
    boolean sawEOS = false;
    int bufferSize = 32000;
    int frameCount = 0;
    int offset = 100;
    ByteBuffer dstBuf = ByteBuffer.allocate(bufferSize);
    MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();
   /* if (degrees >= 0) {
        muxer.setOrientationHint(degrees);
    }*/
    // Test setLocation out of bound cases

    muxer.start();
    while (!sawEOS) {
        bufferInfo.offset = offset;
        bufferInfo.size = extractor.readSampleData(dstBuf, offset);
        if (bufferInfo.size < 0) {

            sawEOS = true;
            bufferInfo.size = 0;
        } else {
            bufferInfo.presentationTimeUs = extractor.getSampleTime();
            bufferInfo.flags = extractor.getSampleFlags();
            int trackIndex = extractor.getSampleTrackIndex();
            muxer.writeSampleData(indexMap.get(trackIndex), dstBuf,
                    bufferInfo);
            extractor.advance();
            frameCount++;

        }
    }
    muxer.stop();
    muxer.release();

    return;
}

退出符号并将迭代器i强制转换为字符串,这样就可以生成一个可行的密钥。