What is Ruby equivalent of Python's `s= hello, %s. Where is %s? % (John,Mary)`
The easiest way is string interpolation. You can inject little pieces of Ruby code directly into your strings.
name1 = "John"
name2 = "Mary"
"hello, #{name1}. Where is #{name2}?"
You can also do format strings in Ruby.
"hello, %s. Where is %s?" % ["John", "Mary"]
Remember to use square brackets there. Ruby doesn't have tuples, just arrays, and those use square brackets.
Is there a Python equivalent to Ruby's string interpolation?
Python 3.6 will add literal string interpolation similar to Ruby's string interpolation. Starting with that version of Python (which is scheduled to be released by the end of 2016), you will be able to include expressions in "f-strings", e.g.
name = "Spongebob Squarepants"
print(f"Who lives in a Pineapple under the sea? {name}.")
Prior to 3.6, the closest you can get to this is
name = "Spongebob Squarepants"
print("Who lives in a Pineapple under the sea? %(name)s." % locals())
The %
operator can be used for string interpolation in Python. The first operand is the string to be interpolated, the second can have different types including a "mapping", mapping field names to the values to be interpolated. Here I used the dictionary of local variables locals()
to map the field name name
to its value as a local variable.
The same code using the .format()
method of recent Python versions would look like this:
name = "Spongebob Squarepants"
print("Who lives in a Pineapple under the sea? {name!s}.".format(**locals()))
There is also the string.Template
class:
tmpl = string.Template("Who lives in a Pineapple under the sea? $name.")
print(tmpl.substitute(name="Spongebob Squarepants"))
Is there an equivalent null prevention on chained attributes of groovy in ruby?
This works in Rails:
my_object.try(:name).try(:capitalize)
If you want it to work in Ruby you have to extend Object
like this:
class Object
##
# @person ? @person.name : nil
# vs
# @person.try(:name)
def try(method)
send method if respond_to? method
end
end
Source
In Rails it's implemented like this:
class Object
def try(*a, &b)
if a.empty? && block_given?
yield self
else
__send__(*a, &b)
end
end
end
class NilClass
def try(*args)
nil
end
end
Using Tuples in Ruby?
OpenStruct?
Brief example:
require 'ostruct'
person = OpenStruct.new
person.name = "John Smith"
person.age = 70
person.pension = 300
puts person.name # -> "John Smith"
puts person.age # -> 70
puts person.address # -> nil
Escaping a variable (containing an array)
Perhaps try string formatting instead. It is not evaluated on creation but rather later.
statement = %|{:foo => %s}|
array = ["a", "b"]
eval(statement % array.inspect) #=> {:foo => ["a", "b"]}
array = [1,2,3]
eval(statement % array.inspect) #=> {:foo => [1, 2, 3]}
Here's another SO question that deals with the above concept
I get highly nervous when I see eval
so I would recommend finding some other way of accomplishing this! However, this should work if you deem there to be no other means.
x not in list, where x contains samples of HELLO speech
MATLAB's .mat
files store one or more variables. numpy
loads those variables as a dictionary where each key corresponds to a variable name and each value corresponds to the value stored in that variable. So x
in your case isn't the HELLO samples, it is a dictionary containing at least one key and the same number of values, where at least one of the values should have your samples. You need to get that value out and store it in x
.
If you know the variable name ahead of time, you can just do this (assume the variable name is 'name'
):
x = sio.loadmat('C:\\Users\\dell\\Desktop\\Rabia Ahmad spring 2016\\FYP\\1. Matlab Work\\record work\\kk.mat')['name']
If you don't know the variable name, but now there will only ever be one variable in the file, you can do this:
myvars = sio.loadmat('C:\\Users\\dell\\Desktop\\Rabia Ahmad spring 2016\\FYP\\1. Matlab Work\\record work\\kk.mat')
x = list(myvars.values)[0]
Also, you don't need to define h
as 'float'
, it will do that automatically since there are decimals in the values. And as AreTor said, you don't need to fill x
with zeros
beforehand, in fact that just wastes time since that array will be immediately discarded and a new one will be created.
Ruby formatting for ordinals: '1' as '1st', '2' as '2nd' etc
Looks like you are looking for ordinalize:
The Ruby on Rails framework is chock full of interesting little nuggets. Ordinalize is a number extension that returns the corresponding ordinal number as a string. For instance, 1.ordinalize returns “1st” and 22.ordinalize return “22nd”.
Example:
place = 3
puts "You are currently in #{place.ordinalize} place."Result:
You are currently in 3rd place.
Which format should the version constant of my project have
First of all, Foo::Version
seems wrong to me. That implicates that version is a Class or a Module, but should be a constant, as first two of your examples.
Apart from that, there is no golden rule here. Here are a few examples:
Rails:
Rails::VERSION::STRING
(Note: a module VERSION
with all capitals.)
SimpleForm:
SimpleForm::VERSION
Nokogiri:
Nokogiri::VERSION
RSpec:
RSpec::Version::STRING
(Note, a module Version
, compare with Rails above.)
Cucumber:
Cucumber::VERSION
SimpleForm:
SimpleForm::VERSION
Most of the above have their version defined in the lib/[name]/version.rb
file, except for Rails, which has a version.rb
in the root of the project, and Cucumber, which has buried it in the lib/cucumber/platform.rb
file.
Also note that all of the above use String
s as a version. (Rails even concatenates MAJOR
, MINOR
, TINY
, and PRE
constants into a single VERSION
constant.) This allows for easy comparison of versions:
"1.2.3" > "0.4.2" # => true
"1.2.3" > "1.2.2" # => true
"1.2.3" > "1.2" # => true
However, such a comparison fails when you run into double digits for the patch level:
"1.2.3" > "1.2.12" # => true
To me, defining Foo::VERSION
is your best bet, define it in lib/foo/version.rb
, and make it a String
value.
Related Topics
Calling the "Source" Command from Subprocess.Popen
Understanding Recursion in Python
Generating HTML Documents in Python
Calling R Script from Python Using Rpy2
How to Get Access of Individual Trees of a Xgboost Model in Python /R
Equivalent to Python's Findall() Method in Ruby
Don't Wait for a Page to Load Using Selenium in Python
Failed to Install Python Cryptography Package with Pip and Setup.Py
Download Returned Zip File from Url
In Python, How to Import Filename Starts with a Number
Why Is Variable1 += Variable2 Much Faster Than Variable1 = Variable1 + Variable2
Generate Correlated Data in Python (3.3)
Size Legend for Plotly Bubble Map/Chart